我正在尝试创建一个返回枚举值的简单脚本,让我们举个例子: //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.
}
}
// Object.class
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;
}
}
}
答案 0 :(得分:10)
您需要致电System.out.print(AnimalID.getAnimal());
答案 1 :(得分: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 name() ": " +animal;
}
@Override
public String toString() {
return this.name() + ": " +animal;
}
}