ran*_*psp 57 java string switch-statement
我需要将以下内容更改if为switch- case同时检查a String,以提高圈复杂度.
String value = some methodx;
if ("apple".equals(value)) {
method1;
}
if ("carrot".equals(value)) {
method2;
}
if ("mango".equals(value)) {
method3;
}
if ("orange".equals(value)) {
method4;
}
Run Code Online (Sandbox Code Playgroud)
但我不确定我会得到什么价值.
nic*_*dos 166
Java(版本7之前)不支持switch/case中的String.但是你可以通过使用枚举来达到预期的效果.
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...
}
Run Code Online (Sandbox Code Playgroud)
cHa*_*Hao 17
学会使用else.
由于value永远不会同时等于两个不相等的字符串,因此只有5种可能的结果 - 一种是您关心的每个值,另外一种是"以上都不是".但是因为你的代码没有消除无法通过的测试,所以它有16个"可能的"路径(2 ^测试次数),其中大部分都不会被遵循.
有else,唯一存在的路径是实际可能发生的5.
String value = some methodx;
if ("apple".equals(value )) {
method1;
}
else if ("carrot".equals(value )) {
method2;
}
else if ("mango".equals(value )) {
method3;
}
else if ("orance".equals(value )) {
method4;
}
Run Code Online (Sandbox Code Playgroud)
或者开始使用JDK 7,它包括在switch语句中使用字符串的能力.当然,Java 无论如何都会编译switch成if/ elselike结构......
Sur*_*gch 17
现在每个人都至少使用Java 7,对吧?以下是原始问题的答案:
String myString = getFruitString();
switch (myString) {
case "apple":
method1();
break;
case "carrot":
method2();
break;
case "mango":
method3();
break;
case "orange":
method4();
break;
}
Run Code Online (Sandbox Code Playgroud)
笔记
要减少圈复杂度,请使用地图:
Map<String,Callable<Object>> map = new HashMap < > ( ) ;
map . put ( "apple" , new Callable<Object> () { public Object call ( method1 ( ) ; return null ; } ) ;
...
map . get ( x ) . call ( ) ;
Run Code Online (Sandbox Code Playgroud)
或多态性