How to return to main menu when exit is inputted

前端 未结 1 901
旧时难觅i
旧时难觅i 2021-01-27 08:43

I want to return to main menu aka \"eventSelection\" if 4 (exit) is selected. Right now I have it as return which exits whole program.

import java.util.*;

publi         


        
相关标签:
1条回答
  • 2021-01-27 09:25

    I used to play with these kind of things too when I first started learning Java. The most simple solution is indeed a while-loop. It evaluates the boolean expression and keeps executing the code within its brackets for as long as the boolean equals 'true'. I refactored your example:

    public static void eventSelection() {
            Scanner sc = new Scanner(System.in);
    
            int actionSelect = 0;
            while (actionSelect != 4) {
                System.out.println("Select Scheduling Action");
                System.out.print("Add an Event = 1. \nDisplay Events = 2.\nPrint Alert = 3. \nExit program = 4. \nINPUT : ");
    
                actionSelect = sc.nextInt();
    
                switch (actionSelect) {
                    case 1:
                        addEvent();
                        break;
                    case 2:
                        displayEvent();
                        break;
                    case 3:
                        printAlert();
                        break;
                    default:
                        break;
                }
            }
            System.out.println("Exited program");
        }
    

    It will now display your menu everytime a number is entered. Except when they enter 4, which now becomes the exit out of your entire program.

    When faced with multiple if-else, it's perhaps better to use a switch-case. It takes a parameter and per case, you can define the action. If the entered parameter doesn't match a case, it falls back to the default (in this case, it does nothing and the program will continue, showing the select menu anyway)

    The 'break' keyword is needed to contain the cases. Otherwise, the next line of code would be executed as well. A bit more information about the switch statement can be found here.

    And ofcourse, here's the link to the while-loops.

    One last tip... As I learned to program, I found that there's nothing more important than to (re)search as much as I could on Google. There are examples aplenty out there.

    0 讨论(0)
提交回复
热议问题