简体   繁体   English

你能简化这个 if 语句吗?

[英]Can you simplify this if-statement?

I am looking to somehow simplify the following: monthNbr==11||monthNbr==4||monthNbr==6||monthNbr==9 here:我希望以某种方式简化以下内容: 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;
    }
}

perhaps it would look nicer with the new switch expressions也许使用新的 switch 表达式会更好看

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

Don't reinvent the wheel:不要重新发明轮子:

Month.of(monthNbr).length(isLeapYear)

Since Java 8, you can also do:由于 Java 8,您还可以这样做:

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

and this will get you the number of the months for the current year.这将为您提供当年的月数。

Also, note, that Switch Expressions can be only used since Java 12.另外,请注意, Switch Expressions只能在 Java 12 之后使用。

Here is one smaller version, it should also be easy to extend to support leap years.这是一个较小的版本,它也应该很容易扩展以支持闰年。 Either by send the year or send year 2000 if you want leap year.如果您想要闰年,请发送年份或发送 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
        
     }
}

You can use stream like this.您可以像这样使用 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