[java] switch (String) 的使用

Posted on 2011-10-27 10:02 yuezt 阅读(2624) 评论(0)  编辑  收藏
switch能够使类似if-else的判断变得简明,但java中switch()不支持string,(jdk1.7支持)。
使用枚举可以弥补这一缺憾。
 1 public class SwitchTest{
 2     public enum Animal{
 3         dog,cat,mouse;
 4         public static Animal getAnimalType(String animal){
 5             return valueOf(animal.toLowerCase());
 6         }
 7     }
 8 
 9     public static void main(String[] args){
10         selectAnimal("cat");
11     }
12 
13     public static void selectAnimal(String animal){
14         switch(Animal.getAnimalType(animal)){
15             case cat:               
16                 System.out.println("this is a cat");
17                 break;
18 
19             case dog:               
20                 System.out.println("this is a dog");
21                 break;
22 
23             case mouse:               
24                 System.out.println("this is a mouse");
25                 break;
26         }
27     }
28 }

只有注册用户登录后才能发表评论。


网站导航: