Challenge: Age Checker
Completed
Create a checked exception InvalidAgeException. Write static void checkAge(int age) throws InvalidAgeException that throws it with the message Age must be 0-120 when the age is outside 0 to 120.
Read n ages. For each, print OK <age> or Error: Age must be 0-120.
Input
First n, then n whole numbers.
Output
One line per age.
Example
Input
3 25 -1 130
Output
OK 25 Error: Age must be 0-120 Error: Age must be 0-120
Editor
Java
Hints
class InvalidAgeException extends Exception, with a constructor calling super(message).
The method header needs throws InvalidAgeException.
Solution explanation
Because the exception is checked, Java makes sure every caller of checkAge deals with it.
Show solution
import java.util.Scanner;
class InvalidAgeException extends Exception {
InvalidAgeException(String message) {
super(message);
}
}
public class Main {
static void checkAge(int age) throws InvalidAgeException {
if (age < 0 || age > 120) {
throw new InvalidAgeException("Age must be 0-120");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
int age = sc.nextInt();
try {
checkAge(age);
System.out.println("OK " + age);
} catch (InvalidAgeException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module