I\'m parsing a doc and I get the following error:
Exception in thread \"main\" java.lang.NumberFormatException: For input string: \"null\"
at sun.misc.Fl
The call of the trim function is useless. If you really want to screen your input data to avoid the NumberFormatException you find the code in the JavaDocs for Doubles
Maybe one of the values is "null" (for example, the string : "123.4 null 5 null"
) not the first one, so I think a proper solution will be:
String[] latValues = latitude.split(" ");
float sum = 0;
for (int i = 0; i < latValues.length; i++) {
if (!latValues[i].equals("null"))
sum = sum + Float.valueOf(latValues[i].trim()).floatValue();
}
latitude = Float.toString(sum / (float) latValues.length);
or instead, add try-cath inside the for loop and ignore values that are not numbers.
EDIT
As pointed in comments (Sualeh), it is better to use try / catch because today it's "null" tomorrow it's something else (i.e. double spaces...).
try {
sum = sum + Float.valueOf(latValues[i].trim()).floatValue();
}
catch (NumberFormatException e)
{
// log e if you want...
}
It is pretty clear that the problem is that you have an input line that has the characters "null"
instead of one of the numbers. But I don't think that ignoring the nulls is necessarily the right thing to do.
First, you need to figure out what those nulls really mean:
Then maybe you need to track down the bug / bugs or adjust your processing to deal with the missing data.
To avoid issues with strings like "1 2", with multiple spaces, which give null values, it is best to add a try-catch inside the loop, like this:
if (latitude != null) {
String[] latValues = latitude.split(" ");
float sum = 0;
for (int i = 0; i < latValues.length; i++) {
try {
sum = sum + Float.valueOf(latValues[i].trim()).floatValue();
} catch (NumberFormatException e) {
e.printStackTrace();
}
}
latitude = Float.toString(sum / (float) latValues.length);
}
The parseInt() and parseDouble() will error with NFE if passed with a null, space or blank string value. Once you have handled the null condition it will still fail with an empty string. Try adding a zero before the empty string like below. It maintains the integrity of calc as well:
Integer.parseInt(" ".trim())
to
Integer.parseInt( "0" + " ".trim())
Based on your error, it is very possible your latValues[i].trim()
displays the value "null
". I'm able to replicate your problem here:-
Float.valueOf("null");
Here's the stacktrace:-
java.lang.NumberFormatException: For input string: "null"
at sun.misc.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1301)
at java.lang.Float.valueOf(Float.java:375)
In another word, the value you have is not null, but it contains the word "null".
If you do Float.valueOf(null);
, that actually gives you a NullPointerException
, which is not what you have here.