I changed Scanner fin = new Scanner(file);
to Scanner fin = new Scanner(new File(file));
and it works perfectly now. I didn't think the difference mattered but there you go.
Got a NumberFormatException while trying to parse a text file for objects
-
23-09-2022 - |
Question
While trying to create objects and add them to an ArrayList using data from a text file, the program threw a NumberFormatException and I have absolutely no clue why, everything seemed OK to me. Here's the method in which the exception occurred:
static void read(String file) {
anime.clear();
try {
Scanner fin = new Scanner(file);
while (fin.hasNextLine()) {
String[] vals = fin.nextLine().split("[ ]");
anime.add(new Anime(Integer.parseInt(vals[0]),
vals[1],
Integer.parseInt(vals[2]),
Integer.parseInt(vals[3])));
}
fin.close();
} catch(Exception e) {
System.out.println("ERROR: Something went wrong!");
e.printStackTrace();
System.exit(-1);
}
}
and here's the text file:
0 Angel_Beats! 13 2010
0 Baccano! 13 2007
0 Bakemonogatari 15 2009
0 Berserk 25 1997
0 Clannad 23 2007
Solution 2
OTHER TIPS
The problem might be your split()
call. Try just split(" ")
without the square brackets.
NumberFormatException invoke when you ll try to convert inavlid String for eg:"abc"
value to integer..
this is
valid string is eg"123"
.
in your case split by space..
split(" ");
will split line by " "
by space..
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow