Java NullPointerException - 短程序

Ibu*_*idu 5 java program-entry-point runtime-error exception nullpointerexception

我是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
Run Code Online (Sandbox Code Playgroud)

我的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
Run Code Online (Sandbox Code Playgroud)

这是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."
);
Run Code Online (Sandbox Code Playgroud)

和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;
    }
}
Run Code Online (Sandbox Code Playgroud)

正如你可以看到我写了2个println-s而且它们都是假的,所以对象存在!我不明白为什么它显示NullPointerException :(

Jon*_*eet 3

如果失败:

this.mines.add(mine); //dies here
Run Code Online (Sandbox Code Playgroud)

...那么我怀疑mines是空引用。您还没有显示任何声明或初始化 - 但这应该是您的第一个停靠点。很可能这只是一个改变的情况:

private List<Mine> mines;
Run Code Online (Sandbox Code Playgroud)

到

private List<Mine> mines = new ArrayList<Mine>();
Run Code Online (Sandbox Code Playgroud)

或类似的东西。