Search code examples
javaparsingnumberformatexception

Got a NumberFormatException while trying to parse a text file for objects


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

  • 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.