我试图让两个空值进行比较,不断在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 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)方法所在对象实例的名称) 任何人都可以提出解决方法吗?
答案 0 :(得分:3)
这是new Double(null)
做的......
编译器必须找到匹配的构造函数。 Double
类有两个构造函数(根据javadoc):
Double(double value)
// Constructs a newly allocated Double object that represents the primitive double argument.
Double(String s)
// Constructs a newly allocated Double object that represents the floating-point value of type double represented by the string.
null
不是基本类型的有效值(即small-d double
),因此这会导致尝试调用第二个构造函数,该构造函数需要String
。然后,它在运行时尝试以double
的格式解析字符串。这导致NullPointerException
,因为String
参数为null。 [更确切地说,我认为在某个时候会有来自s.trim()
的{{1}}来电,如果sun.misc.FloatingDecimal
是s
则会引发异常。] < / p>
答案 1 :(得分:1)
您正在调用空指针异常,因为您正在调用
new Double(null);
这不是你使用Double构造函数的方式。要传回null,只需返回null。您可以通过将此行更改为:
来解决此问题return null;