using java, Create a full program that will have a user enter in a person\'s age
ID: 3861649 • Letter: U
Question
using java, Create a full program that will have a user enter in a person's age and if age is negative it will catch the exception and display an error message Sorry age must be positive. It will test the age and if age is under 5 or greater than 55 it will display you pay 5.50 and if any other positive age it will say you pay 11.00. All interaction can be done on the console.It will also have a method in the exception that will be giveSecondChance() that will allow user to reenter a positive age if a negative one is entered
Explanation / Answer
AgeDemo.java
import java.util.Scanner;
public class AgeDemo {
// Scanner object is used to get the inputs entered by the user
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
int age;
System.out.print("Enter Person's Age :");
age = sc.nextInt();
while(true)
{
try {
if (age < 0)
throw new Exception("Sorry age must be positive");
else if (age < 5 || age > 55)
{
System.out.println("You pay 5.50");
break;
}
else
{
System.out.println("You pay 11.00");
break;
}
} catch (Exception e) {
System.out.println(e);
age=giveSecondChance();
continue;
}
}
}
private static int giveSecondChance() {
System.out.print("Re-enter a positive age :");
int age = sc.nextInt();
return age;
}
}
_______________
Output:
Enter Person's Age :-45
java.lang.Exception: Sorry age must be positive
Re-enter a positive age :57
You pay 5.50
_____________Thank You
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.