繁体   English   中英

你能简化这个 if 语句吗?

[英]Can you simplify this if-statement?

我希望以某种方式简化以下内容: 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;
    }
}

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

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

不要重新发明轮子:

Month.of(monthNbr).length(isLeapYear)

由于 Java 8,您还可以这样做:

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

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

另外,请注意, Switch Expressions只能在 Java 12 之后使用。

这是一个较小的版本,它也应该很容易扩展以支持闰年。 如果您想要闰年,请发送年份或发送 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
        
     }
}

您可以像这样使用 stream 。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM