当我尝试调用方法 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)
最佳答案
这看起来肯定是背包还没有初始化。使用像
这样的构造函数可能是值得的public class Rebel{
private final Map<String, Item> backpack;
public Rebel(Map<String, Item> backpack, <Other parameters){
this.backpack = backpack;
}
public Rebel(<Other parameters>){
this(new HashMap<String,Item>(),<Other parameters>);
}
}
显然正在替换 <Other parameters>
使用当前的构造函数参数。
关于java - Java 中使用 BlueJ 的 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15396603/