-3
此代碼拋出NullPointerException。Java - 代碼總是拋出NullPointerException
protected static Integer cost;
public static int incCost(int value)
{
cost += value;
};
此代碼拋出NullPointerException。Java - 代碼總是拋出NullPointerException
protected static Integer cost;
public static int incCost(int value)
{
cost += value;
};
由於引用類型的默認值是null
,不0
。
protected static Integer cost = 0; //<-- add = 0
或者,使用原始int
像
protected static int cost; //<-- defaults to 0.
你也必須返回一個int
,所以你可以做
public static int incCost(int value)
{
cost += value;
return cost;
}
你永遠不會初始化成本,你需要做的
protected static Integer cost = 0;
因爲你不能添加一個數字到未初始化的對象;