Home > Blockchain >  Have an issue with Integer.parseInt(string)
Have an issue with Integer.parseInt(string)

Time:11-15

Scanner input = new Scanner (System.in);
        String str = input.nextLine();  // reads x , y
        int x = Integer.parseInt(str.substring(0, str.indexOf(",")));   // this reads the numbers until comma
                                                                                                                                    
        System.out.println(x);
        

when i do this i don't get an error

22, 23

but when i do this

22 ,23

i get the following error:

Exception in thread "main" java.lang.NumberFormatException: For input string: "22 "
    at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:68)
    at java.base/java.lang.Integer.parseInt(Integer.java:652)
    at java.base/java.lang.Integer.parseInt(Integer.java:770)
    at scratchFiles.stringArray.main(stringArray.java:9)

CodePudding user response:

Use trim() to return a copy of the string, with leading and trailing whitespace removed so that it can be parsed to an Int:

public static void main(String[] args) {
    Scanner input = new Scanner (System.in);
    String str = input.nextLine();  // reads x , y
    int x = Integer.parseInt(str.substring(0, str.indexOf(",")).trim());
    System.out.println(x);
}

CodePudding user response:

The problem is when you try to get the first number the string returned from substring from "22 , 23" is "22[whitespace]". With Integer.parseInt() you can only pass an integer string as a parameter otherwise it will through an error.

public static void main(String[] args) {
    Scanner input = new Scanner (System.in);
    String str = input.nextLine();  // reads x , y
    // get string till , and remove any trailing whitespaces
    String numString = str.substring(0, str.indexOf(",")).trim();
    int x = Integer.parseInt(numString);
    System.out.println(x);
}

There are few things you should be careful about if string is something like this "22 3, 34" you will still get an exception. So be careful about sanitizing your string first and then pass it to Integer.parseInt()

  • Related