在Java中,Double和double经常交替使用,经常不予区别。但今天遇到一个空指针异常,原因是Double可以为null,而double作为基本数据类型不能为null,因此就出现了Exception in thread "main" java.lang.NullPointerException这个报错,解决方法就是当Double转doule时,先进行null判断,或者统一使用Double对象。
public class Main {
public static void main(String[] args) {
double d = getDouble("0");
double d1 = getDouble(null);
double d2 = getDouble("-0.2");
System.out.println("d:"+d);
System.out.println("d1:"+d1);
System.out.println("d2:"+d2);
}
public static Double getDouble(String s){
if(null == s) {
return null;
}
return Double.parseDouble(s);
}
}
d:0.0
Exception in thread "main" java.lang.NullPointerException
at com.xxx.xxx.Main.main(Main.java:7)
public static void main(String[] args) {
double d = getDouble("0");
System.out.println("d:"+d);
Double d1 = getDouble(null);
System.out.println("d1:"+d1);
}
public static Double getDouble(String s){
if(null == s) {
return null;
}
return Double.parseDouble(s);
}
d:0.0
d1:null
在Java编程中,Double是对象,可以为null,而double是基本数据类型,不能为null。这导致了在进行类型转换时可能遇到NullPointerException。解决方法是在转换前对Double对象进行null检查。示例代码展示了如何避免这种异常,通过在调用Double.parseDouble()前检查输入字符串是否为null。
17万+

被折叠的 条评论
为什么被折叠?



