1

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;
   }
Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
Johnny Van
  • 87
  • 1
  • 10
  • 4
    looks like you need to trim the leading blank from the string value `" 12"`. – Filburt Sep 24 '18 at 11:37
  • [Converting a String with spaces to an Integer in java](https://stackoverflow.com/questions/23851668/converting-a-string-with-spaces-to-an-integer-in-java) (although I'd say you should be fixing your regex instead of doing this) – Bernhard Barker Sep 24 '18 at 12:33

2 Answers2

2

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

Andrew Tobilko
  • 48,120
  • 14
  • 91
  • 142
1

Try to split with ", " or ",\\s".

dnsiv
  • 520
  • 4
  • 20