[java] switch (String) 的使用

          Posted on 2011-10-27 10:02 yuezt 閱讀(2631) 評論(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 }

          只有注冊用戶登錄后才能發(fā)表評論。


          網(wǎng)站導航:
           
          主站蜘蛛池模板: 钦州市| 桂阳县| 工布江达县| 大邑县| 宾阳县| 翼城县| 武陟县| 鹿泉市| 沈阳市| 桓台县| 晴隆县| 汽车| 万年县| 秭归县| 吉木萨尔县| 潼南县| 岳阳市| 周宁县| 肇州县| 鹿泉市| 云安县| 锡林浩特市| 高密市| 牙克石市| 离岛区| 永胜县| 临沂市| 辽宁省| 罗平县| 阜宁县| 合川市| 大田县| 宁津县| 师宗县| 青河县| 龙海市| 溆浦县| 饶平县| 怀集县| 简阳市| 双峰县|