Use string in switch case in java

前端 未结 13 1783
盖世英雄少女心
盖世英雄少女心 2020-12-01 07:30

I need to change the following if\'s to a switch-case while checking for a String, to improve the cyclomatic complexity.<

13条回答
  •  不知归路
    2020-12-01 07:39

    Java (before version 7) does not support String in switch/case. But you can achieve the desired result by using an enum.

    private enum Fruit {
        apple, carrot, mango, orange;
    }
    
    String value; // assume input
    Fruit fruit = Fruit.valueOf(value); // surround with try/catch
    
    switch(fruit) {
        case apple:
            method1;
            break;
        case carrot:
            method2;
            break;
        // etc...
    }
    

提交回复
热议问题