用戶輸入 1-12 的整數代表月份,程序輸出該月天數。需考慮 2 月閏年情況。
int[] days = {31,28,31,30,31,30,31,31,30,31,30,31}; 索引 0 對應 1 月。(year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)。若為閏年且月份為 2,天數 +1。import java.util.Scanner;
public class MonthDays {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("請輸入年份: ");
int year = sc.nextInt();
System.out.print("請輸入月份(1-12): ");
int month = sc.nextInt();
if (month < 1 || month > 12) {
System.out.println("月份輸入錯誤!");
return;
}
int[] days = {31,28,31,30,31,30,31,31,30,31,30,31};
boolean leap = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);
if (leap && month == 2) days[1] = 29;
System.out.printf("%d 年 %d 月 有 %d 天%n", year, month, days[month - 1]);
}
}
java.time.YearMonth (Java 8+) 一行搞定:YearMonth.of(year, month).lengthOfMonth()。InputMismatchException 捕獲非數字輸入。基礎語法練習,邏輯清晰是關鍵。