if (linestyle == 5 || linestyle == 21 || linestyle == 82 || linestyle == 83 || linestyle == 3) {
linestyleString = "DOUBLE";
} else if (linestyle == 6 || linestyle == 35 || linestyle == 39 || linestyle == 30) {
linestyleString = "DottED" ;
} else if (linestyle == 26 || linestyle == 27 || linestyle == 28 || linestyle == 29 || linestyle == 1) {
linestyleString = "SOLID";
} else if(linestyle == -1) {
linestyleString = "NONE";
}
我们如何在Java中以智能方式处理此代码?切换案例,枚举或密钥对值模式?
最佳答案
您的条件看起来更随机.
Switch在这里看起来不错
switch(linestyle) {
case 5:
case 21:
case 82:
case 83:
case 3:
linestyleString = "DOUBLE";
break;
.. // add more cases
}
或者我更喜欢创建实用方法
public static boolean contains(int expecxted,int... vals) {
for (int i = 0; i < vals.length; i++) {
if (expecxted == vals[i]) {
return true;
}
}
return false;
}
你可以像使用它一样
if (contains(linestyle,5,21,82,83,3)) {
linestyleString = "DOUBLE";
} else if(contains(linestyle,6,35,39,30)){
linestyleString = "DottED";
}