1

当我尝试调用方法 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)
4

1 回答 1

1

这绝对看起来像背包还没有初始化。可能值得使用像这样的构造函数

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>为您当前的构造函数参数。

于 2013-03-13T22:15:33.503 回答