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";
}

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...