问题
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:
linetakes in stdintempgets filled with each of the individual single-digit values (split("") splits after every character)- Each digit (stored as a
String) is parsed as anintand added toartemp - 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 ""?
回答1:
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]));
}
回答2:
From The Docs parseInt
Throws:
NumberFormatException - if the string does not contain a parsable integer.
So your Code artemp.add(Integer.parseInt(temp[i])); is some where encoutering a unparsable String.
回答3:
your split("")is null ,you should write split(" ") (double quote with a space)
回答4:
Rather than using split, I'd think using the string itself will be better. Try this.
Scanner test = new Scanner(System.in);
String[] temp = null;
String line = null;
ArrayList<Integer> artemp = new ArrayList<>();
while(test.hasNext()) {
line = test.next();
for(int i = 0; i < line.length; i++)
artemp.add(Integer.parseInt(""+line.charAt(i));
for(int i : artemp) System.out.println(i);
}
来源:https://stackoverflow.com/questions/18952433/numberformatexception-for-input-string-while-parsing