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中巧妙地处理这些代码呢?切换大小写、枚举或密钥对值模式?
发布于 2017-07-18 18:25:30
你的情况看起来更随机。
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";
}发布于 2017-07-18 18:27:32
一个缩进良好的交换机案例需要30行行(Netbeans建议自己进行转换,以便我可以计数)
所以我认为这种方式更好(9行):
if (Arrays.asList(5, 21, 82, 83, 3).contains(lineStyle)) {
lineStyleString = "DOUBLE";
} else if (Arrays.asList(6, 35, 39, 30).contains(lineStyle)) {
lineStyleString = "DOTTED";
} else if (Arrays.asList(26, 27, 28, 29, 1).contains(lineStyle)) {
lineStyleString = "SOLID";
}else if (lineStyle == -1) {
lineStyleString = "NONE";
}发布于 2017-07-18 18:36:47
我更喜欢这样的枚举:
enum LineStyle {
DOUBLE(3, 5, 21, 82, 83),
DOTTED(6, 30, 35, 39),
SOLID(1, 26, 27, 28, 29),
NONE(-1);
private final Set<Integer> types;
private LineStyle(Integer... types) {
this.types = Stream.of(types).collect(Collectors.toSet());
}
public static LineStyle of(int lineStyle) {
return Stream.of(LineStyle.values())
.filter(ls -> ls.types.contains(lineStyle))
.findFirst().orElse(null);
}
}然后您可以简单地调用:LineStyle ls = LineStyle.of(lineStyle);
https://stackoverflow.com/questions/45163963
复制相似问题