1

我正在尝试制作一个简单的脚本来返回枚举的值,让我们举个例子://EG.class(应该返回动物 ID。

import Object.Animal;

public class EG {
    public void main() {
        Animal AnimalID = Object.Animal.CAT;

        System.out.print(AnimalID);
        //Should return value of CAT: 2000 (long)
        //But I can't figure out what's wrong.
    }
}

//对象.类

public class Object {
    public enum Animal {
        CAT(2000L), DOG(2001L), MONKEY(2002L), TIGER(2003L);

        private long animal;

        private Animal(long a) {
          animal = a;
        }

        public long getAnimal() {
          return animal;
        }
    }
}
4

2 回答 2

10

你需要打电话System.out.print(AnimalID.getAnimal());

于 2012-08-08T21:08:09.967 回答
6

为什么不在枚举上创建一个toString()方法?Animal

public enum Animal {
    CAT(2000L), DOG(2001L), MONKEY(2002L), TIGER(2003L);

    private long animal;

    private Animal(long a) {
      animal = a;
    }

    public long getAnimal() {
      return animal;
    }

    @Override
    public String toString() { 
       return this.name() + ": " +animal;
    }
}
于 2012-08-08T21:08:48.897 回答