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?
Instead of using the s.nextInt(), parse the first token to an Integer.
See the example below.
This results in the list to be populated.