Search code examples
javaarraysnumberformatexception

Error : Exception in thread "main" java.lang.NumberFormatException: For input string: ""


I am trying to input numbers as a string and splitting and storing them in a string array and then later storing them as integers in int array. I have tried quite a few things like .trim() or scanner.skip() but am unable to solve this issue here.

My Input:

4 
1 2 2 2

 public static void main(String []args) throws IOException{

    Scanner scanner = new Scanner(System.in);
    int arCount = scanner.nextInt();
    int[] ar = new int[arCount];
    String[] arItems = scanner.nextLine().split(" ");

    for (int i = 0; i < arCount; i++) {
        int arItem = Integer.parseInt(arItems[i].trim());
        ar[i] = arItem;
    }
    scanner.close();
 }

The error received is:

Exception in thread "main" java.lang.NumberFormatException: For input string: ""
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:592)
at java.lang.Integer.parseInt(Integer.java:615)
at Hello.main(Hello.java:32)

Solution

  • Why don't you just use the nextInt() method over and over again (bypassing the use of split totally), like so,

    import java.util.*;
    
    public class MyClass {
        public static void main(String []args){
    
        Scanner scanner = new Scanner(System.in);
        int arCount = scanner.nextInt();
    
        int[] ar = new int[arCount];
        for(int i=0;i<arCount;i++){
            ar[i] = scanner.nextInt();;
        }
        System.out.println(Arrays.toString(ar));
    
        scanner.close();
     }
    }
    

    UPDATE:

    In your original program, you are using nextInt() method first, which does not consume the newline character '\n'. So, the next invocation of nextLine() actually consumes the newline character on the same line instead of the line below that which contains the integers for your array. So, for your code to work properly, you can modify it slightly as follows,

    import java.util.*;
    
    public class MyClass {
        public static void main(String []args){
    
        Scanner scanner = new Scanner(System.in);
        int arCount = scanner.nextInt(); // doesn't consume \n
        int[] ar = new int[arCount];
        scanner.nextLine(); //consumes \n on same line 
        String line = scanner.nextLine(); // line is the string containing array numbers
        System.out.println(line);
        String[] arItems = line.trim().split(" "); //trim the line first, just in case there are extra spaces somewhere in the input
        System.out.println(Arrays.toString(arItems));
        for (int i = 0; i < arCount; i++) {
            int arItem = Integer.parseInt(arItems[i].trim());
            ar[i] = arItem;
        }
        System.out.println(Arrays.toString(arItems));
     }
    }