Loading...
Loading...
An exam form asks for the date of birth as dd-mm-yyyy. Write a method checkDate(String text) that throws an IllegalArgumentException with the reason when the date is wrong. Check in this order:
use the form dd-mm-yyyy if splitting on - does not give exactly 3 parts,parseInt throws NumberFormatException),year must be 1 to 9999,month must be 1 to 12,day must be 1 to D, where D is the number of days in that month (29 for February in a leap year).A leap year is divisible by 4 but not by 100, or divisible by 400. For each line print Valid: <text>, Invalid: <text> (not a number) or Invalid: <text> (<reason>). Finish with Valid dates: V of n.
Valid dates: V of n.intExample 1
Input
4 15-08-2025 29-02-2024 29-02-2023 31-04-2025
Output
Valid: 15-08-2025 Valid: 29-02-2024 Invalid: 29-02-2023 (day must be 1 to 28) Invalid: 31-04-2025 (day must be 1 to 30) Valid dates: 2 of 4
2024 is a leap year; 2023 is not. April has 30 days.
Example 2
Input
3 15/08/2025 15-13-2025 1O-01-2025
Output
Invalid: 15/08/2025 (use the form dd-mm-yyyy) Invalid: 15-13-2025 (month must be 1 to 12) Invalid: 1O-01-2025 (not a number) Valid dates: 0 of 3
Try the problem first. Open one hint at a time.
Inside checkDate, split on -, check the length, then parse the three parts.
Keep the days of each month in an array {31, 28, 31, 30, ...} and use 29 when the month is 2 and the year is a leap year.
In main, catch NumberFormatException before IllegalArgumentException, because it is a kind of IllegalArgumentException.
Write your Java code, run it on the examples and submit it to hidden tests.
Solve in the editor