Dieser Code löst eine NullPointerException aus.Java - Code wirft immer NullPointerException
protected static Integer cost;
public static int incCost(int value)
{
cost += value;
};
Dieser Code löst eine NullPointerException aus.Java - Code wirft immer NullPointerException
protected static Integer cost;
public static int incCost(int value)
{
cost += value;
};
Da der Standardwert von Referenztypen ist null
, nicht 0
.
protected static Integer cost = 0; //<-- add = 0
Oder verwenden Sie eine primitive int
wie
protected static int cost; //<-- defaults to 0.
Sie müssen auch ein int
zurückkehren, so dass Sie
public static int incCost(int value)
{
cost += value;
return cost;
}
Sie nie initialisiert Kosten tun könnten, müssten Sie
tunprotected static Integer cost = 0;
weil Sie einem nicht initialisierten Objekt keine Nummer hinzufügen können;