Search code examples
javaintegernumberformatexceptionparseint

This code throws an exception for the line Integer.parseInt(data[2])


In my playerList.txt I have lines constructed as such:

Nathaniel, Clyne, 12, first

Why can't it accept Integer.parseInt?

I have a class MemberPlayer that defines a MemberPlayer should have the first name, last name, age and team (first or second).

Exception in thread "main" java.lang.NumberFormatException: For input string: " 12"
at java.base/java.lang.NumberFormatException.forInputString NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:638)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at FileHandler.getContent(FileHandler.java:53)
at Main.main(Main.java:55)

   public static final String FINAL_PATH = "playerList.txt";

   public static ArrayList<MemberPlayer> getContent(String FINAL_PATH)
     {
        ArrayList<MemberPlayer> list = new ArrayList<MemberPlayer>();
        try
        {
              Scanner sc = new Scanner(new File(FINAL_PATH));
              while(sc.hasNextLine())
              {                                   
                    String data[] = sc.nextLine().split(",");
                    list.add(new MemberPlayer(data[0], data[1], 
                    Integer.parseInt(data[2]), data[3]));
              }

        }
        catch(FileNotFoundException e)
        {

        }
        return list;
   }

Solution

  • " 12" can't be parsed into a valid int because it has a leading space, but "12" can:

    Integer.parseInt(data[2].trim())
    

    Make sure that all of data[0] ... data[3] exist before accessing them. The file might be corrupted or inaccurately filled.