依照格里高利曆規則:
public class LeapYearCheck {
public static void main(String[] args) {
int year = 2024; // 測試年份
if (isLeapYear(year)) {
System.out.println(year + " 是閏年");
} else {
System.out.println(year + " 是平年");
}
}
/**
* 判斷閏年
* @param year 年份
* @return true=閏年, false=平年
*/
public static boolean isLeapYear(int year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
}
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) {
System.out.println(year + "是閏年");
} else {
System.out.println(year + "是平年");
}
| 年份 | 預期結果 | 說明 |
|---|---|---|
| 2000 | 閏年 | 能被 400 整除 |
| 1900 | 平年 | 能被 100 整除但非 400 |
| 2024 | 閏年 | 能被 4 整除、非 100 |
| 2023 | 平年 | 不能被 4 整除 |
import java.time.Year;
public class LeapYearJava8 {
public static void main(String[] args) {
int year = 2024;
boolean leap = Year.of(year).isLeap();
System.out.println(year + (leap ? " 是閏年" : " 是平年"));
}
}
java.time.Year 內建閏年判斷,語意更清晰,推薦現代專案使用。
閏年判斷邏輯簡單但易寫錯(常漏掉 100/400 例外)。封裝為靜態工具方法或直接使用 Year.isLeap(),可提升代碼可讀性與複用性。