我正在尝试弄清楚如何在 Java 中使用枚举,但我不知道该怎么做:
public enum animalSounds {
CAT("meow"),
DOG("Woof"),
PIG("Oink"),
public final String animalName;
animalSounds(String noise) {
this.animalName = noise
}
}
我正在尝试做的是传入一个字符串,并查看该字符串是否存在于可枚举集合中。因此,我会传入“Oink”并取回 PIG,但如果我传入“Chirp”,我会得到某种错误,因为“Chirp”没有枚举值。
最佳答案
枚举不是你想要做的最好的事情,但你可以尝试
private animalSounds getAnimal(String noise) {
for(animalSounds a : animalSounds.values())
{
if(a.animalName.equals(noise))
{
return a;
}
}
throw new IllegalArgumentException();
}
关于java - 如何检查 Java 枚举中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5546635/