Search code examples
javanumberformatexception

Why is parseInt in java unable to identify integers in my input string?


After inputting a string and separating it into different parts, I have used parseInt to separate integers from an input string. But while running the program, a NumberFormatException generated on the string " 4", which clearly has the integer '4' in it. input is a file reading scanner type variable already declared in the program prior to this operation.

String line = input.nextLine();
String[] part = line.split(",  ");

int tempParticleNumber;

tempParticleNumber = Integer.parseInt(part[0]);

The terminal output is

Exception in thread "main" java.lang.NumberFormatException: For input string: "      4"
        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)

Expected process is that the input string " 4" is converted to an integer 4, but this doesn't happen.


Solution

  • Simply trim() the whitespaces:

    tempParticleNumber = Integer.parseInt(part[0].trim());