邏輯表達式:(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
import java.util.Scanner;
public class LeapYearChecker {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("請輸入年份:");
long year = sc.nextLong();
boolean isLeap = isLeapYear(year);
System.out.println(year + (isLeap ? " 是閏年" : " 不是閏年"));
}
/**
* 判斷閏年
* @param year 年份 (支援長整數範圍)
* @return true=閏年, false=平年
*/
public static boolean isLeapYear(long year) {
return (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
}
}
import java.time.Year;
import java.time.chrono.IsoChronology;
public class ModernLeapYear {
public static void main(String[] args) {
int year = 2024;
// 方式 1:Year 類
boolean leap1 = Year.of(year).isLeap();
// 方式 2:Chronology
boolean leap2 = IsoChronology.INSTANCE.isLeapYear(year);
System.out.println(year + " -> " + leap1);
}
}
year % 4 == 0 → 1900 會被誤判為閏年。int 接收年份,若處理古曆/未來遠年份可能溢位,建議用 long 或 Year。public static int daysInMonth(int year, int month) {
switch (month) {
case 2: return isLeapYear(year) ? 29 : 28;
case 4: case 6: case 9: case 11: return 30;
default: return 31;
}
}
// 或直接用 YearMonth.of(year, month).lengthOfMonth() (JDK 8+)
閏年判斷是經典邏輯練習,掌握「400 年 97 次閏」的規則並正確轉為布林表達式是關鍵。實務開發中,優先使用 java.time 套件,避免手寫邏輯出錯。