給定出生日期(格式 YYYY-MM-DD),計算從出生到 18 歲生日共經過多少天。若該人尚無 18 歲生日(如出生日期為 2010-02-29 且 2028 年無 2 月 29 日),輸出 -1。
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Scanner;
public class Birthday18 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int T = sc.nextInt();
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("yyyy-MM-dd");
while (T-- > 0) {
String s = sc.next();
try {
LocalDate birth = LocalDate.parse(s, fmt);
LocalDate target = birth.plusYears(18);
// 若出生是 2 月 29 日且目標年非閏年,plusYears 會自動調整為 2 月 28 日
// 題目要求若無 18 歲生日則輸出 -1,需額外判斷
if (birth.getMonthValue() == 2 && birth.getDayOfMonth() == 29 && !target.isLeapYear()) {
System.out.println(-1);
} else {
long days = ChronoUnit.DAYS.between(birth, target);
System.out.println(days);
}
} catch (Exception e) {
System.out.println(-1);
}
}
}
}
輸入 1988-03-07,輸出 6574,包含 5 個閏年(1992,1996,2000,2004,2008),計算正確。
利用 java.time 包簡化日期運算,避免手動處理閏年邏輯出錯。