How to return to main menu in switch case after ex

2020-08-01 06:42发布

How do I get get the menu to display again after the selected method executes?

I have the menu option print to the console. Then it takes user input (1 - 6), calls according method, and then should return to the menu for the user to select from the menu again.

After the selected method executes, the program just ends.

public static void main (String[] arg) {

    Scanner kbd = new Scanner(System.in);

    String mainMenu = ("Select a choice from the menu: \n" 
            + "1. Add new DVD entry\n" 
            + "2. Look Up DVD Entry\n"
            + "3. Display DVDs By Category\n" 
            + "4. Remove DVD Entry\n"
            + "5. Save Data\n" 
            + "6. Exit");

    System.out.println(mainMenu);

    menuChoice = kbd.nextInt();

    while (menuChoice < 1 || menuChoice > 6) {
        System.out.print("\nError! Incorrect choice.\n");
        System.out.println(mainMenu);
        menuChoice = kbd.nextInt();
    }

    switch (menuChoice) {
    case 1: {
        // method code
        }
        else {
            // method code
            return;
        }
    }

    case 2: {
        // method code
        return;
    }

    case 3: {
        // method code
        return;
    }

    case 4: {
        // method code
        return;
    }   

    case 5: {
        // method code
        return;
    }

    case 6: {
        // method code
        System.exit(0);
        return;
    }
    }
}

标签: java
2条回答
【Aperson】
2楼-- · 2020-08-01 07:12

Use a do while

do
{
    System.out.println(mainMenu);

    menuChoice = kbd.nextInt();

   ... switch/case ...
   ... remove the return statements from your cases.

} while (menuChoice != 6);

You also have to remove the return from your cases. Otherwise it will return out of main. Replace them with break;

This is how switch cases need to be

switch (menuChoice) 
{
    case 1: 
        Do what you want. 
        break;
    case 2:
        ...
        break;
    default:
        ...
        break;
}

You don't usually need { or if inside the switch case.

查看更多
混吃等死
3楼-- · 2020-08-01 07:22

wrap your code inside

  while(menuChoice != 6) 
    { 
      ... 
    }
查看更多
登录 后发表回答