簡體   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