輸入年月日,計算該日期是當年的第幾天。核心在於各月天數累加與閏年修正。本文提供 switch 累加法與 LocalDate 現代 API 兩種實作。
boolean isLeap = (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
import java.util.Scanner;
public class DayOfYearCalculator {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("請輸入 年 月 日(空格分隔):");
int year = sc.nextInt();
int month = sc.nextInt();
int day = sc.nextInt();
sc.close();
int sum = 0;
switch (month) {
case 12: sum += 30;
case 11: sum += 31;
case 10: sum += 30;
case 9: sum += 31;
case 8: sum += 31;
case 7: sum += 30;
case 6: sum += 31;
case 5: sum += 30;
case 4: sum += 31;
case 3: sum += 28; // 非閏年 2 月
case 2: sum += 31;
case 1: break;
default:
System.out.println("月份錯誤"); return;
}
sum += day;
if (isLeapYear(year) && month > 2) sum++;
System.out.printf("%d-%02d-%02d 是 %d 年的第 %d 天%n", year, month, day, year, sum);
}
static boolean isLeapYear(int y) {
return (y % 400 == 0) || (y % 4 == 0 && y % 100 != 0);
}
}
技巧:switch 故意省略 break,利用貫穿特性由下往上累加,程式碼簡潔。
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Scanner;
public class ModernDayOfYear {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("請輸入日期 (yyyy-MM-dd):");
String input = sc.nextLine();
sc.close();
LocalDate date = LocalDate.parse(input, DateTimeFormatter.ISO_LOCAL_DATE);
int dayOfYear = date.getDayOfYear();
System.out.printf("%s 是 %d 年的第 %d 天%n", input, date.getYear(), dayOfYear);
}
}
優點:自動處理閏年、月份天數、時區、曆法切換,程式碼極簡且無 Bug。
static final int[] NORMAL = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
static final int[] LEAP = {0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335};
public static int dayOfYear(int y, int m, int d) {
return (isLeapYear(y) ? LEAP : NORMAL)[m-1] + d;
}
| 輸入 | 輸出 | 說明 |
|---|---|---|
| 2024-03-01 | 61 | 閏年 2 月 29 天,3/1 為第 61 天 |
| 2023-03-01 | 60 | 平年 2 月 28 天 |
| 2000-12-31 | 366 | 閏年最後一天 |
| 1900-12-31 | 365 | 1900 非閏年(100 整除但非 400) |
現代專案直接用 LocalDate.getDayOfYear();教學、嵌入式或無 Java 8+ 環境時,switch 貫穿累加或陣列查表法均可,關鍵是正確判斷閏年並在 2 月後修正。