輸入年、月、日,輸出該日期是當年的第幾天。需處理閏年 2 月 29 日情況。
import java.util.Scanner;
public class DayOfYear {
private static final int[] MONTH_DAYS = {0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334}; // 1-base 索引對應月份前累積天數
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();
if (month < 1 || month > 12 || day < 1 || day > 31) {
System.out.println("日期錯誤");
return;
}
int dayOfYear = MONTH_DAYS[month - 1] + day;
// 閏年判斷:能被 400 整除,或被 4 整除但不被 100 整除
boolean isLeap = (year % 400 == 0) || (year % 4 == 0 && year % 100 != 0);
if (isLeap && month > 2) {
dayOfYear++;
}
System.out.println("這是當年的第 " + dayOfYear + " 天");
}
}
import java.time.LocalDate;
import java.time.temporal.ChronoField;
public class DayOfYearModern {
public static void main(String[] args) {
LocalDate date = LocalDate.of(2024, 3, 1);
int dayOfYear = date.get(ChronoField.DAY_OF_YEAR);
System.out.println(dayOfYear); // 61 (閏年)
}
}
java.time 內建處理閏年、月份長度、時區等複雜細節,生產環境首選。