[英]null pointer exception. why?
我是 Java 新手,如果这个问题听起来很愚蠢,请原谅我。 我在学习。
我正在尝试计算这个总和,但收到一条奇怪的错误消息。 你能帮我找到它在哪里吗? 非常感谢
public class myfirstjavaclass {
public static void main(String[] args) {
Integer myfirstinteger = new Integer(1);
Integer mysecondinteger = new Integer(2);
Integer mythirdinteger = null;
Integer result = myfirstinteger/mythirdinteger;
}
}
Exception in thread "main" java.lang.NullPointerException
at myfirstjavaclass.main(myfirstjavaclass.java:8)
您不应该在此处使用Integer
(对象类型),因为它可以为null
(您不需要并在这里绊倒)。
当您在 Java 中取消引用null
时,您会收到 NullPointerException。
在这种情况下,它有点棘手,因为涉及自动拆箱(原始类型与其对象包装器之间转换的花哨名称)。 幕后发生的事情是
Integer result = myfirstinteger/mythirdinteger;
真的编译为
Integer result = Integer.valueOf(
myfirstinteger.intValue() / mythirdinteger.intValue());
对intValue()
的调用在空指针上失败。
只需使用int
(原语)。
public static void main(String[] args) {
int myfirstinteger = 1;
int mysecondinteger = 2;
int mythirdinteger = 0;
int result = myfirstinteger/mythirdinteger;
// will still fail, you cannot divide by 0
}
在我看来,您的第三个整数被分配给了空值。
BTW,你真的想做什么? 如果您想计算您在问题中所说的总和,请参阅下面的代码
public static void main(String[] args) {
int first = 1;
int second = 2;
int third = 0;
int sum = first + second + third;
}
如果要计算乘积,请确保没有除以 0
public static void main(String[] args) {
int first = 1;
int second = 2;
int product = first / second; // this product is 0, because you are forcing an int
double product2 = (double) first / second; // this will be 0.5
}
“空”的意思是“这个变量没有引用任何东西”,这是“这个变量没有值”的另一种说法。 这并不意味着“价值为零”。
NullPointerException 是当您在需要变量具有值的上下文中使用不引用任何内容的变量时 Java 给您的异常。 一个数字除以一个变量的值是一个上下文,它要求变量具有一个值——因此是例外。
因为你除以null
,当然。 你期待发生什么?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.