private static int[] daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
我正在尋找一種方法,如果年份 % 4 == 0 那么 daysInMonth[1] = 29
uj5u.com熱心網友回復:
你可以檢查它是否是閏年。如果是,則二月有 29 天。
private static int[] daysInMonth = {31 , LocalDate.now().isLeapYear() ? 29:28 ,
31 , 30 , 31 , 30 , 31 , 31 , 30 , 31 , 30 , 31};
uj5u.com熱心網友回復:
雖然問題不是很清楚,但我會嘗試回答。
您似乎要問的是,當您訪問 daysInMonth[1] 時,您需要它根據您使用的年份是動態的。
如果您希望使用 daysInMonth[1],那么不使用 lamdas 或方法參考作為陣列而不是整數是不可能的。
相反,我建議您通過訪問器方法訪問值,如下所示:
public int daysOfMonth(int year, int month) {
if (month == 1 && year % 4 == 0) {
return 29;
}
return daysInMonth[1];
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/386277.html
