java写一个有异常处理机制的生日计算代码
时间: 2024-05-29 17:08:53 浏览: 61
好的,以下是这段代码:
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.Scanner;
public class BirthdayCalculator {
public static void main(String[] args) {
System.out.print("请输入您的生日日期(格式:yyyy-MM-dd):");
Scanner scanner = new Scanner(System.in);
String input = scanner.nextLine();
try {
LocalDate birthday = LocalDate.parse(input, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDate today = LocalDate.now();
int age = today.getYear() - birthday.getYear();
if (today.getMonthValue() < birthday.getMonthValue()
|| (today.getMonthValue() == birthday.getMonthValue() && today.getDayOfMonth() < birthday.getDayOfMonth())) {
age--;
}
System.out.println("你的年龄是:" + age);
} catch (DateTimeParseException e) {
System.out.println("输入的日期格式不正确!");
}
}
}
希望能对您有所帮助!
阅读全文