在我的程序中,我有一个名为Hive的类,其中包含Honey,Pollen,royalJelly和几种蜜蜂的数组列表。某些蜜蜂的食用方法彼此之间几乎相同,不同之处在于它们的食用量或食用量。每个蜜蜂都有一个anotherDay方法,该方法调用蜜蜂上的eat方法,在蜂巢的anotherDay方法中,它循环遍历数组列表,从而调用每个蜜蜂anotherDay。我的皇后蜂吃得很好,但是当我在工人,无人机或幼虫上吃东西时,出现NullPointerException,我不知道为什么!我的代码:

蜂巢类:

public class Hive {

    ArrayList<Bee> cells = new ArrayList<Bee>();
    int honey = 10;
    int royalJelly = 10;
    int pollen = 10;             //some methods omitted

    public void anotherDay(){
        ArrayList<Bee> dead = new ArrayList<Bee>();
        int size = cells.size();

        for(int i = 0; i < size; i++) {
            Bee bee = cells.get(i);

            if ((bee = bee.anotherDay()) == null) {
                dead.add(cells.get(i));
            } else {
                cells.set(i, bee);
            }
        }
        cells.removeAll(dead);
    }


Queen类:(此类中的eat方法不会获得空指针异常)

public class Queen extends Bee{

    Hive hive = null;

    public Queen(){
    }

    public Queen(Hive hive){
        this.hive = hive;
        this.type = 1;
        this.age = 11;
        this.health = 3;
    }

    public Bee anotherDay(){
        eat();
        if (health == 0) {
            return null;
        }
        age++;
        if (age % 3 == 2) {
            hive.addBee(new Egg());
        }
        return this;
    }

    public boolean eat(){
        if(hive.honey >= 2) {
            hive.takeHoney(2);
            if(health < 3){
                health++;
            }
            return true;
        }
        health -= 1;
        return false;
    }
}


工蜂类:(获取NullPointerException-不知道为什么)

public class Worker extends Bee {

    Hive hive = null;

    public Worker(){
        this.type = 2;
        this.age=11;
        this.health=3;
    }

    public Bee anotherDay(){
        eat();
        age++;
        if (health == 0) {
            return null;
        }
        return this;
    }

    public boolean eat(){
        if(hive.honey >= 1) {
            hive.takeHoney(1);
            if(health < 3){
                health++;
            }
            return true;
        }
        health -= 1;
        return false;
    }
}


例外:

Exception in thread "main" java.lang.NullPointerException
    at Larvae.eat(Larvae.java:26)
    at Larvae.anotherDay(Larvae.java:13)
    at Hive.anotherDay(Hive.java:86)
    at TestBasicHive.testpart4(TestBasicHive.java:381)
    at TestBasicHive.main(TestBasicHive.java:13)


我将元素添加到arraylist中,代码运行良好,直到出现幼虫/工人或无人机,并尝试使用eat方法。如果我注释掉运行eat方法的位,它将运行良好(但显然不执行我想要的操作)

从给出的答案中,我尝试将worker类中的构造函数更改为:

public Worker(Hive hive){
    this.hive=hive;
    this.type = 2;
    this.age=11;
    this.health=3;
}

public Worker(){}


我需要“空”构造函数,因为工蜂是通过pupa中的anotherDay方法添加到配置单元中的,即:

public Bee anotherDay(){
    age++;
    if(age>10){
        return new Worker();
    }return this;
}


然后通过蜂巢中的anotherDay方法将其添加到arraylist中。

最佳答案

hive初始化为null,并且在您的Worker类中从未更改。然后在eat方法中尝试访问一个字段。

08-04 00:15