你能简化这个 if 语句吗?

时间:2021-03-14 00:18:23

标签: java simplify

我希望以某种方式简化以下内容:monthNbr==11||monthNbr==4||monthNbr==6||monthNbr==9 此处:

public int daysPerMonth (int monthNbr){
    if(monthNbr==11||monthNbr==4||monthNbr==6||monthNbr==9){
        return 30;
    } else if (monthNbr==2) {
        return 28;
    } else {
        return 31;
    }
}

5 个答案:

答案 0 :(得分:5)

也许用新的 switch 表达式看起来会更好

public int daysPerMonth(int monthNbr) {
    return switch (monthNbr) {
        case 11, 4, 6, 9 -> 30;
        case 2 -> 28;
        default -> 31;
    };
}

答案 1 :(得分:4)

不要重新发明轮子:

Month.of(monthNbr).length(isLeapYear)

答案 2 :(得分:0)

从 Java 8 开始,您还可以:

public int daysPerMonth(int monthNbr) {
    return YearMonth.of(Year.now().getValue(),monthNbr).lengthOfMonth();
}

这将为您提供当前年份的月份数。

另外,请注意,Switch Expressions 只能从 Java 12 开始使用。

答案 3 :(得分:0)

这是一个较小的版本,它也应该很容易扩展以支持闰年。如果你想要闰年,要么发送年份,要么发送 2000 年。

import java.util.*; 
import java.time.*;

public class HelloDays
{
     public static int daysPerMonth(int monthNbr)
     {
        YearMonth yearMonthObject = YearMonth.of(1999, monthNbr);
        return yearMonthObject.lengthOfMonth();  
     }
     
     public static void main(String []args)
     {
        System.out.println(daysPerMonth(1));  // 31
        System.out.println(daysPerMonth(2));  // 28
        System.out.println(daysPerMonth(4));  // 30
        
     }
}

答案 4 :(得分:0)

您可以像这样使用流。

public int daysPerMonth(int monthNbr) {
    if (IntStream.of(11, 4, 6, 9).anyMatch(i -> monthNbr == i)) {
        return 30;
    } else if (monthNbr == 2) {
        return 28;
    } else {
        return 31;
    }
}