【问题标题】:NullPointerException in Java with BlueJ带有 BlueJ 的 Java 中的 NullPointerException
【发布时间】: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


【解决方案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>);
    }
}

显然将&lt;Other parameters&gt; 替换为您当前的构造函数参数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-10-17
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多