我正在创建一个新的Attendace对象。第一个参数生成我随机的动物,可以正常工作
完美,但是,如果我检查随机动物是否是猫,它仍会返回假,也可能是
猫,我的错误可能是什么?

 public enum Animal{
            DOG,
            CAT,
            HORSE
            }

            public class Attendace {
                private Animal animal;
                private boolean present;
                private static int count;

                public Attendace (Animal animal, boolean present) {
                    this.animal = animal;
                    this.present= present;
                }

                public Attendace() {}

                public static boolean presence{
                 Attendace a = new Attendace();
                 if(a.animal == Animal.CAT && count == 0){
                  ++count;
                  return true;
                 }
                 return false
                }
            }


            new Attendace(Animal.randomEnum(), Attendace.presence());

);

最佳答案

presence中,您正在创建Attendance的新实例,而没有为其赋予Animal,这意味着animal保持为null

相反,将presence更改为此:

public boolean presence() {
    int count = 0;
    if (animal == Animal.CAT && count == 0) {
        ++count;
        return true;
    }
    return false;
}


...从构造函数中删除boolean presence,而是调用函数。

public Attendace (Animal animal) {
    this.animal = animal;
    this.present = presence();
}

10-08 18:27