Java 空指针异常。为什么?

Java 空指针异常。为什么?,java,nullpointerexception,Java,Nullpointerexception,我是java新手,所以如果这个问题听起来很愚蠢,请原谅我。我在学习 我试图计算这个总数,但我得到一个奇怪的错误消息。你能帮我找到它在哪里吗?多谢各位 public class myfirstjavaclass { public static void main(String[] args) { Integer myfirstinteger = new Integer(1); Integer mysecondinteger = new Integer(2)

我是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)

当然,因为你除以了
null
。您希望发生什么?

您不应该在此处使用
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 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
}
“Null”表示“此变量不引用任何内容”,这是表示“此变量没有值”的另一种方式。这并不意味着“值为零”


NullPointerException是Java在要求变量具有值的上下文中使用不引用任何内容的变量时提供的。用一个数字除以一个变量的值是一个上下文,它要求变量有一个值,因此出现了异常。

只是一个提示:
(myfirstjavaclass.java:8)
意味着它发生在第8行。该行上是否有任何空指针(“引用”)“为什么它不是零?”-因为这不是C。由于运算符的原因,对象类型正在转换为文本类型。然而,空值不能转换成文字,所以你会得到这个例外。@Mary:我想说的是-你可能会发现你第一次遇到这种情况时非常不安。遗憾的是,我们是一个面向有编程经验的用户的用户群。请不要让这阻碍您学习编程。祝你好运“面向具有一定编程经验的用户的用户群。”其中有一部分人似乎忘记了他们也曾经是新手。为什么试图除以null会引发NullPointerException?为什么不使用DivideByNullException或其他更具解释性的异常呢?答案并不是那么简单,正如@ChrisDennett在评论中指出的那样。。。OP是新手,你不必粗鲁。@AshBurlaczenko关于自动拳击,请随意提供更详细的答案。@mellamokb我本可以将此作为评论发布,但它也是一个答案,所以我将其作为答案发布。我不知道为什么除以
null
得到一个异常是令人惊讶的。标准做法是在SO问题上快速给出不完整的答案。如果你的问题是如此不完整,以至于评论和答案是可以互换的,我不会真的拿回答者出气。
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
}