Espon
Espon

Reputation: 11

How to return to main menu with switch cases

I need to return to main menu when 3 is selected. My main menu code is another loop that I have not included as code but I just want to return to it.(The first loop is in main).

Here is my code:

public static void addEvent() {
    while (true) {
        boolean valid = false;

        do {
            Scanner sc = new Scanner(System.in);
            System.out.println("What type of event is it?");
            System.out.println("Lecture = 1. \nWorkshop = 2. \nReturn to Main Menu = 3. \nExit Program = 4. \nINPUT : ");
            int action = sc.nextInt();
            valid = true;

            switch (action) {
                case 1:
                    valid = true;
                    lectureEvent();
                    break;
                case 2:
                    valid = true;
                    workshopEvent();
                    break;
                case 3:
                    valid = true;
                    break;
                case 4:
                    valid = true;
                    return;
                default:
                    valid = false;
                    System.out.println("ERROR : Choice " + action + "Does not exist.");
                    System.out.println("Please choose an alternative.");
            }
        } while (!valid);
    }
}

Upvotes: 0

Views: 1458

Answers (1)

Do it like you did it in case 4, replace the break for a return

switch (action) {
     case 1:
           valid = true;
           lectureEvent();
           break;
      case 2:
           valid = true;
           workshopEvent();
           break;
      case 3:
           valid = true;
           return;
      case 4:
           valid = true;
           return;
      default:
           valid = false;
           System.out.println("ERROR : Choice " + action + "Does not exist.");
           System.out.println("Please choose an alternative.");
 }

Upvotes: 1

Related Questions