2011-04-05 82 views
2

我试图找出如何在Java中使用枚举了,我不明白如何做到这一点:如何检查Java枚举中的值?

public enum animalSounds { 
    CAT("meow"), 
    DOG("Woof"), 
    PIG("Oink"), 

    public final String animalName; 

    animalSounds(String noise) { 
     this.animalName = noise 
    } 

} 

我想要做的,是在传递一个字符串,看如果该字符串存在于一组枚举中。所以,我会传入“Oink”并返回PIG,但如果传入“Chirp”,我会得到某种错误,因为“Chirp”没有枚举值。

+0

它看起来像每个答案的驱动器倒票,但我不明白为什么。 – trashgod 2011-04-05 17:00:33

回答

0

枚举不适合你正在尝试做的最好的事情,但你可以尝试

private animalSounds getAnimal(String noise) { 
    for(animalSounds a : animalSounds.values()) 
    { 
     if(a.animalName.equals(noise)) 
     { 
      return a; 
     } 
    } 
    throw new IllegalArgumentException(); 
} 
+0

+1“第60项:赞成使用标准例外” - [Bloch](http://java.sun.com/docs/books/effective/)。 – trashgod 2011-04-05 16:58:18

0

使用值()方法 - 与遍历不同类型的,做你的逻辑。

0

对于少数几个,遍历values();对于很多人来说,创建一个Map<String, AnimalSounds>,建议here