java.lang.NumberFormatException: For input string: “null”

后端 未结 6 1309
独厮守ぢ
独厮守ぢ 2020-12-21 05:16

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         


        
6条回答
  •  一个人的身影
    2020-12-21 05:51

    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...
    }
    

提交回复
热议问题