I've got a main menu I'm creating for a program using a switch statement. I'm try to set up Try and Catch Exception so that if a user enters a String rather than an Int, the program will tell the user this is not valid and prompt them to try again.
So far, I have gotten it to tell the user this is not valid whenever this occurs, but it is unable to go back and take an input from the user.
Here is my code:
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("Subscription Manager:");
System.out.println("\n1. Enter new Subscription");
System.out.println("2. Display Summary of subscriptions");
System.out.println("3. Display Summary of subscription for Selected Month");
System.out.println("4. Find and display subscription");
System.out.println("0. Exit");
System.out.print("Please choose one of the options to proceed:");
try {
int choice = sc.nextInt();
switch (choice) {
case 1:
System.out.println("1. Enter new Subscription");
break;
case 2:
System.out.println("2. Display Summary of subscriptions");
break;
case 3:
System.out.println("3. Display Summary of subscription for Selected Month");
break;
case 4:
System.out.println("4. Find and display subscription");
break;
case 0:
System.out.println("Exiting Program...");
System.out.println("Goodbye!");
System.exit(1);
break;
default:
System.out.println("ERROR. Enter a selection from the options to continue!");
break;
}
} catch (InputMismatchException e) {
System.out.println("Enter a numerical value!");
sc.nextLine();
}
}
}
I have tried adding a do while loop, but I am met with the same issue still. Thank you for reading!
CodePudding user response:
What you need to do is to use a loop with the correct exit condition. For this specific case, I would recommend using do..while
loop. Because this looks like a school assignment, I am not going to give you the full code but a small pseudocode.
int choice = 9999; // Declare this outside the do while loop so that you can access this variable in the while exit clause.
// Also initialize this so that you still have a value for choice in case of exception
do {
try {
int choice = sc.nextInt();
// DO YOUR SWITCH CASE AS YOU HAVE
}
catch(InputMismatchException e) {
// IN this case, choice is still 9999 for an error in the first run and some other integer in the subsequent runs of the loop. Just print an error message.
}
} while (choice != 0);