java.lang.NumberFormatException:对于输入字符串:" null" [英] java.lang.NumberFormatException: For input string: "null"
问题描述
我正在解析文档但是我收到以下错误:
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);
//}
}
如你所见,我试过检查null字符串,但即使取消注释第二个if语句,我也会得到相同的错误。
As you can see I've tried to check for "null" strings but even uncommenting the second if statement I get the same error.
谢谢
推荐答案
可能其中一个值为null(例如,字符串:123.4 null 5 null
)不是第一个,所以我认为一个合适的解决方案是:
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);
或者在for循环中添加try-cath并忽略非数字的值。
or instead, add try-cath inside the for loop and ignore values that are not numbers.
编辑
正如评论(Sualeh)所指出的,最好使用试试/ catch因为今天明天它是null它是别的东西(即双倍空格......)。
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...
}
这篇关于java.lang.NumberFormatException:对于输入字符串:" null"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!