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

你能简化这个 if 语句吗?

如何解决你能简化这个 if 语句吗?

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

您可以像这样使用流。

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

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