Throwing Exceptions

Lab Java Intermediate 20 points

Write static int checkedAge(int age) that throws IllegalArgumentException("invalid age: AGE") unless 0 ≤ age ≤ 150. Read ages and print each valid age or the exception message.

Input

n, then n integers.

Output

n lines.

Example

Input

3
30
-4
200

Output

30
invalid age: -4
invalid age: 200
Sample input available Sample output available
Editor
Java

Hints

throw new IllegalArgumentException("...") stops the method.

getMessage() returns the message text.

Solution explanation

Validating arguments and throwing early keeps bad data from spreading through a program.

Show solution
import java.util.Scanner;

public class Main {
    static int checkedAge(int age) {
        if (age < 0 || age > 150) {
            throw new IllegalArgumentException("invalid age: " + age);
        }
        return age;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        for (int i = 0; i < n; i++) {
            try {
                System.out.println(checkedAge(sc.nextInt()));
            } catch (IllegalArgumentException e) {
                System.out.println(e.getMessage());
            }
        }
    }
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD