Search code examples
javajava.util.scannerparseint

Why is the Integer.parseInt not working in my java code?


import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Scanner;

public class MainProgram {
   public static void main(String[] args ) throws IOException{
    String seconds = " ";

     Scanner sc2 = null;
        try {
            sc2 = new Scanner(new File("/Users/mohammadmuntasir/Downloads/customersfile.txt"));
        } catch (FileNotFoundException e) {
            e.printStackTrace();  
        }

        boolean first = true;
        while (sc2.hasNextLine()) {
                Scanner s2 = new Scanner(sc2.nextLine());    
            while (s2.hasNext()) {
                String s = s2.next();
                if (first == true){
                    seconds = s;
                    first = false;
                }

            }
        }
        System.out.println(Integer.parseInt(seconds)); // causes ERROR?

     }
 }

I am trying to read a number from a text file which is in the first line by itself. I made an integer called seconds that will take in the first number and will be parsed into an integer. But I always get a numbers exception error and that I can't parse it. When I display s as a string, it displays a number without spaces next to it. Can anyone explain why this happens?

Here is the stacktrace:

Exception in thread "main" java.lang.NumberFormatException: For input string: "300" 
  at java.lang.NumberFormatException.forInputString(NumberFormatE‌xception.java:65) 
  at java.lang.Integer.parseInt(Integer.java:580) 
  at java.lang.Integer.parseInt(Integer.java:615) 
  at MainProgram.main(MainProgram.java:29)

Solution

  • If the exception message is really this:

     java.lang.NumberFormatException: For input string: "300"
    

    then we are starting to get into really obscure causes.

    • It could be a problem with homoglyphs; i.e. Unicode characters that look like one character but are actually different characters.

    • It could be a non-printing character. For example an ASCII NUL ... or a Unicode BOM (Byte Order Marker) character.

    I can think of three ways to diagnose this:

    1. Run your code in a debugger and set a breakpoint on the parseInt method. Then look at the String object that you are trying to parse, checking its length (say N) and the first N char values in the character array.

    2. Use a file tool to examine the file as bytes. (On UNIX / Linux / MacOSX, use the od command.)

    3. Add some code to get the string as an array of characters. For each array entry, cast the char to an int and print the resulting number.

    All three ways should tell you exactly what the characters in the string are, and that should explain why parseInt thinks they are wrong.


    Another possibility is that you copied the exception message incorrectly. The stacktrace was a bit mangled by the time you got it into the Question ...