java – 处理智能方式的条件

前端之家收集整理的这篇文章主要介绍了java – 处理智能方式的条件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

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";
}
原文链接:https://www.f2er.com/java/437394.html

猜你在找的Java相关文章