【发布时间】:2012-11-06 07:24:52
【问题描述】:
我是 Java 编程新手,我不明白我的代码中发生了什么。
它告诉我:
Exception in thread "main" java.lang.NullPointerException
at Main.Country.addMine(Country.java:37)
at Main.Main.main(Main.java:21)
Java Result: 1
我的 main.java 很简单:
Continent Europe = new Continent("Europe");
Country asd = new Country("asd", Europe);
Mine mine = new Mine(100,100,100,100);
System.out.println(mine == null);
asd.addMine(mine); //dies here
这是 addMine 方法:
public void addMine(Mine mine) {
System.out.println(mine == null);
this.mines.add(mine); //dies here
this.iron += mine.iron;
this.gold += mine.gold;
this.stone += mine.stone;
this.wood += mine.wood;
System.out.println("Mine has been successfully added to the country with the given values."
);
而 Mine.java 是:
public class Mine implements Building { //Building is an empty interface :)
protected int iron;
protected int gold;
protected int stone;
protected int wood;
public Mine(int iron, int gold, int stone, int wood) {
this.iron += iron;
this.gold += gold;
this.stone += stone;
this.wood += wood;
}
}
如你所见,我写了 2 个 println-s,它们都是假的,所以对象存在!我不明白为什么它显示 NullPointerException :(
【问题讨论】:
-
我猜“地雷”是 Country 的某种动态列表?在您尝试添加之前它是否已初始化?
-
你初始化地雷了吗?我猜这是一个数组列表。
-
你能告诉我们你是如何声明
mines的吗? -
@JeremyD:它不能是数组,因为数组没有
add方法。 -
@JonSkeet 是的,我在想一个数组列表,但输入错误:)
标签: java exception nullpointerexception runtime-error main