当我尝试调用方法 BuyItem,以便 Rebel 类可以从 Item 类中购买物品时,我收到以下消息:
java.lang.NullPointerException: null
我觉得我一直在尝试一切,有人看到代码中有什么问题吗?
这是我的方法:
public boolean buyItem(Item item) {
int totalWeight = currentWeight() + item.getWeight();
if(totalWeight <= maxCarryingCapacity && money >= item.getPrice()){
money -= item.getPrice();
backpack.put(item.getName(), item);
return true;
} else {
return false;
}
}
和
/**
* @param item
* @return current carrying weight
*/
private int currentWeight() {
int tempWeight = 0;
for(Entry<String, Item> entry: backpack.entrySet()) {
tempWeight += entry.getValue().getWeight();
}
return tempWeight;
}
如果你们中的任何人可以帮助我,我会非常高兴,因为我卡住了!
错误是 currentWeight 中的第二行和 buyItem 中的第一行。终端窗口显示:
rebel1.buyItem(item1)
Exception occurred.
java.lang.NullPointerException
at Rebel.currentWeight(Rebel.java:190)
at Rebel.buyItem(Rebel.java:56)