How to read a line from a txt file with int and String elements?

67 views Asked by At

I'm trying to create a List by reading a txt file. For example:

12345; Mary Jane ; 20
12365; Annabelle Gibson; NA

Each line contains: number; name; Grade (grade can be a String or a int)

I created the following method;

public static  List <Pauta>leFicheiro( String nomeF) throws       FileNotFoundException{
    List<Pauta> pautaT = new LinkedList<Pauta>();
    try {
    Scanner s = new Scanner(new File (nomeF));
        try{
            List<Pauta> pautaS =pautaT;
            while ( s.hasNextLine()){
                String line = s.nextLine();
                String tokens[]= line.split(";");
                if(s.hasNextInt()) {
                    System.out.println ("next int = " + s.nextInt());
            }
                pautaS.add(new Pauta (s.nextInt(), tokens[1],tokens[2]);
            }
            pautaT = pautaS;
        }
    finally {
        s.close();
    }
    }
        catch (FileNotFoundException e){
            e.printStackTrace();
        }
        catch (ParseException e){
            e.printStackTrace();
        }       
    return pautaT;
}

Pauta is a class that receives as arguments ( int, String, String), I thought Grade as a String to make it more simple, but if you have ideas on how to still create a List (main goal) by having it String or int I would be thankful.

Now the problem is: The part s.nextInt() is returning error : InputMismatchException

So I put this following code:

catch (InputMismatchException e) {
System.out.print(e.getMessage());}

which says it returns a null.

How can I solve this?

2

There are 2 answers

0
Reg On

Instead of using the s.nextInt(), parse the first token to an Integer.

See the example below.

public static void main(String... args) throws FileNotFoundException {
        List<Pauta> pautaT = new LinkedList<Pauta>();
        try {
            Scanner s = new Scanner(new File("test.txt"));
            try{
                List<Pauta> pautaS =pautaT;
                while ( s.hasNextLine()){
                    String line = s.nextLine();
                    String tokens[]= line.split(";");
                    pautaS.add(new Pauta (Integer.parseInt(tokens[0]), tokens[1],tokens[2]));
                }
                pautaT = pautaS;
            }
            finally {
                s.close();
            }
        }
        catch (FileNotFoundException e){
            e.printStackTrace();
        }

    }

This results in the list to be populated.

0
CarlosMorente On

Yo may use StringTokenizer and save each token of the same line into a variable and then use them as you want.