Search code examples
javanumberformatexception

NumberFormatException: For input string: "" while parsing


I wished to turn a string of single digit integers into an Integer ArrayList, and I'm getting a very odd exception. Here's the sample code:

    Scanner test = new Scanner(System.in);
    String[] temp = null;
    String line = null;
    ArrayList<Integer> artemp = new ArrayList<>();

    while(test.hasNext()) {
        line = test.next();
        temp = line.split("");
        for(int i = 0; i < temp.length; i++)
        artemp.add(Integer.parseInt(temp[i]));
        for(int i : artemp) System.out.println(i);

    }

It is basically supposed to read the string of ints from stdin, put them in an arraylist as primitives, and then print them out. Of course, this is just a small test case to which I narrowed down my larger error.

The exception this raises is the following:

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:504)
    at java.lang.Integer.parseInt(Integer.java:527)

As far as I can see, the following should take place:

  1. line takes in stdin
  2. temp gets filled with each of the individual single-digit values (split("") splits after every character)
  3. Each digit (stored as a String) is parsed as an int and added to artemp
  4. Print out each digit.

What exactly is going wrong here? If I print out temp with the following code:

for(String s : temp) System.out.println(s);

Then the digits get printed successfully (as Strings), and I there are no extra characters. How exactly could parseInt(temp[i]) be getting applied to the string ""?


Solution

  • First of all I'm suspecting your split,

      temp = line.split("");
    

    If you want to split with space ,it should be

      temp = line.split(" ");
    

    And if you want with "" only,then here is the cause.

    There is nothing to do with conversion.

    There are some empty strings in you array.

    So exception while converting empty string in to integer.

    here

     artemp.add(Integer.parseInt(temp[i]));
    

    What you can do is,check the data before parsing.

    if(temp[i]!=null && !temp[i].isEmpty()){
              artemp.add(Integer.parseInt(temp[i]));
    }