Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.NumberFormatException: For input string: "null"

Tags:

java

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.FloatingDecimal.readJavaFormatString(FloatingDecimal.java:1222)
    at java.lang.Float.valueOf(Float.java:388)
    at CentroidGenerator$Centroid.averageLat(CentroidGenerator.java:403)
    at CentroidGenerator.getCentroids(CentroidGenerator.java:30)
    at CentroidGenerator.main(CentroidGenerator.java:139)

This is the part of code throwing the exception:

if (latitude!=null) {
    //if (!latitude.equals("null")) {
        String[] latValues = latitude.split(" ");
    float sum = 0;
    for (int i = 0; i < latValues.length; i++) {                
        sum = sum + Float.valueOf(latValues[i].trim()).floatValue();
    }
    latitude = Float.toString(sum / (float) latValues.length);
    //}
}   

As you can see I've tried to check for "null" strings but even uncommenting the second if statement I get the same error.

thanks

like image 720
aneuryzm Avatar asked Mar 25 '11 13:03

aneuryzm


1 Answers

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...
}
like image 112
MByD Avatar answered Oct 25 '22 21:10

MByD