如何将这个if else-if语句变成Java中的简短形式?

时间:2017-10-28 10:42:29

标签: java

public static double eMED(int emo) {
    double result = 0;

    if (emo >= 40 && emo < 60) {
        result = upFunc(emo, 40, 60);
    } else if (emo > 60 && emo <= 80) {
        result = downFunc(emo, 60, 80);
    } else if (emo == 60) {
        result = 1;
    }
    return result;
}

2 个答案:

答案 0 :(得分:0)

您的代码看起来很短。你不能缩短它。您可以使用三元运算符,但代码几乎不可读。

    return emo == 60 ? 1 
            : emo >= 40 && emo < 60 ? upFunc(emo, 40, 60) 
            : emo > 60 && emo <= 80 ? downFunc(emo, 60, 80) 
            : 0;

答案 1 :(得分:-3)

用例很短

示例:

public class SwitchDemo {
    public static void main(String[] args) {

        int month = 8;
        String monthString;
        switch (month) {
            case 1:  monthString = "January";
                     break;
            case 2:  monthString = "February";
                     break;
            case 3:  monthString = "March";
                     break;
            case 4:  monthString = "April";
                     break;
            case 5:  monthString = "May";
                     break;
            case 6:  monthString = "June";
                     break;
            case 7:  monthString = "July";
                     break;
            case 8:  monthString = "August";
                     break;
            case 9:  monthString = "September";
                     break;
            case 10: monthString = "October";
                     break;
            case 11: monthString = "November";
                     break;
            case 12: monthString = "December";
                     break;
            default: monthString = "Invalid month";
                     break;
        }
        System.out.println(monthString);
    }
}