微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.jb51.cc/java/437394.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐