【发布时间】:2013-03-02 01:18:03
【问题描述】:
当我尝试调用方法 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)
【问题讨论】:
-
异常在哪一行?我假设 item 不为空。还是这样?
-
首先,在发生崩溃的地方添加完整的异常堆栈跟踪和完整的源代码。仅部分代码我们无法为您提供帮助。
-
是的,我们需要更多才能继续下去。这里有很多东西可能是空的。
-
嗯,真的,有两个可能的 null 候选者:背包和物品。我猜它是背包,因为它同时出现在这两种方法中。
-
我希望你现在得到了你需要的信息:)
标签: java nullpointerexception bluej