我是 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 :(