Write a Java application called GradedExercise2 that fulfills this specification
ID: 3750130 • Letter: W
Question
Write a Java application called GradedExercise2 that fulfills this specification. You may be able to reuse some of the code for GradedExercise1 Ask the user for their age. If their age is under 21, or over 100, the program throws an exception.
And the program ends.
If the user’s age is between 21 and 100, the program outputs:
Your age is: (whatever the user has entered).
And the program ends.
If the user enters a number which is less than 21, the program outputs the following, and continues to accept input from the user until the user enters an age between 21 and 100.
java.util.InputMismatchException: You must enter a valid age.
That age is too low. Please try again.
Please enter your age:
If the user enters a number which is greater than 21, the program outputs the following, and continues to accept input from the user until the user enters an age between 21 and 100.
java.util.InputMismatchException: You must enter a valid age.
That age is too high. Please try again.
Please enter your age:
Suggestion: Declare a variable to store the user’s age in main(), and before the loop, or the try. This is because the variable needs to be visible from all trys and catches.
Explanation / Answer
Java code:
import java.util.InputMismatchException;
import java.util.Scanner;
//class
public class GradedExercise2 {
//main method starts
public static void main(String[]arg) {
//Scanner object to read inputs
Scanner scan = new Scanner(System.in);
//Declare a variable to store the user’s age
int age;
//do-while loop till user enters correct age
do
{
System.out.print("Please enter your age:");
age=scan.nextInt();
//try-cacth block
try
{
//if age is below 21 or age is above 100,then throw an exception.
if(age < 21 || age > 100)
throw new InputMismatchException("You must enter a valid age.");
else
System.out.println("Your age is:"+age);
System.exit(0);
}catch(InputMismatchException e)
{
System.out.println(e);
if(age < 21)
System.out.println("That age is too low. Please try again.");
else if(age > 100)
System.out.println("That age is too high. Please try again.");
}
}while(age>=21 || age <=100);
}
}
Output: Test case 1
Please enter your age:20
java.util.InputMismatchException: You must enter a valid age.
That age is too low. Please try again.
Please enter your age:21
Your age is:21
Output: Test case 2:
Please enter your age:103
java.util.InputMismatchException: You must enter a valid age.
That age is too high. Please try again.
Please enter your age:101
java.util.InputMismatchException: You must enter a valid age.
That age is too high. Please try again.
Please enter your age:100
Your age is:100