Java 比较两个Null,获取NullPointerException
我试图比较两个空值,在Eclipse中不断抛出java.lang.NullPointerExceptionJava 比较两个Null,获取NullPointerException,java,Java,我试图比较两个空值,在Eclipse中不断抛出java.lang.NullPointerException public Double x(String x){ if (x.split(" ")[1].equals("+")) { // Ignore this stuff, it works this.x = Double.valueOf(x.split(" ")[0]); return new Doubl
public Double x(String x){
if (x.split(" ")[1].equals("+")) {
// Ignore this stuff, it works
this.x = Double.valueOf(x.split(" ")[0]);
return new Double(x(Double.valueOf(x.split(" ")[2])));
} else if (x.split(" ")[1].equals("x")) {
// Ignore this stuff, it works
this.x = Double.valueOf(x.split(" ")[0]);
return new Double(x(Double.parseDouble(x.split(" ")[2])));
} else {
// The problem
return new Double(null);
}
}
public boolean testParser() {
boolean parseOne;
boolean parseTwo;
boolean parseThree;
if (calc.x("12 + 5") == 17) {
System.out.println("[ OK ] Parser adds correctly.");
parseOne = true;
} else {
System.out.println("[FAIL] Basic parsing fails to add.");
parseOne = false;
}
if (calc.x("12 x 5") == 60) {
System.out.println("[ OK ] Parser multiplies correctly.");
parseTwo = true;
} else {
System.out.println("[FAIL] Basic parsing fails to multiply.");
parseTwo = false;
}
// Comparing null with null here not working
if (calc.x("12 [ 3") == null) {
System.out.println("[ OK ] Parser returns null for operators which are not supported.");
parseThree = true;
} else {
System.out.println("[FAIL] Parser does not return null for operators which are not supported.");
parseThree = false;
}
return (parseOne && parseTwo && parseThree);
}
(其中calc只是Double x(String x)方法所在对象实例的名称)
有人能建议一种解决方法吗?由于您正在调用
new Double(null);
这不是使用双构造函数的方式。要传回null,只需返回null。您可以通过将此行更改为:
return null;
您正在获取空指针异常,因为您正在调用
new Double(null);
这不是使用双构造函数的方式。要传回null,只需返回null。您可以通过将此行更改为:
return null;
以下是
新的双精度(null)
所做的
编译器必须找到匹配的构造函数。Double
类有两个构造函数(根据
null
不是基元类型的有效值(即small-ddouble
),因此这会导致尝试调用第二个构造函数,该构造函数使用字符串。在运行时,它会尝试以double
的格式解析字符串。这会导致NullPointerException
,因为String
参数为null。[更准确地说,我认为在某个时候会有一个类调用sun.misc.FloatingDecimal
调用s.trim()
,如果s
为null
,这是新的双精度(null)
所做的
编译器必须找到匹配的构造函数。Double
类有两个构造函数(根据
null
不是基元类型的有效值(即small-ddouble
),因此这会导致尝试调用第二个构造函数,该构造函数使用字符串。在运行时,它会尝试以double
的格式解析字符串。这会导致NullPointerException
,因为String
参数为null。[更准确地说,我认为在某个时候会有一个类sun.misc.FloatingDecimal
调用s.trim()
,如果s
是null
,这个新的双精度(null)
不是null
,它会抛出一个异常。这与问题无关,但:不要在标题中添加[Java],您已经用Java
标记了您的问题。此新双精度(null)
不是null
。与问题无关,但:不要在标题中添加[Java],您已经用Java
标记了您的问题。