[英]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.