如何在 Java 中保持 switch 语句继续

我希望重复以下菜单:

选择一个选项

1 - 查找

2 - 随机播放

3 - 洗牌

这样当用户选择一个选项时(这将被执行),之后他们也可以选择其他选项.

So that when a user selects an option (and this will be executed), afterwards they can select other options as well.

问题:我的代码使菜单不断重复.

Problem: My code keeps the menu repeating without stopping.

import java.util.Scanner;

public class MainMenu {
    public static void main(String[] args) {
        int userChoice;
        userChoice = menu();
    }

    private static int menu() {
        Scanner scanner = new Scanner(System.in);
        System.out.println("Choose an Option");
        System.out.println("1 - FIND");
        System.out.println("2 - IN-SHUFFLE");
        System.out.println("3 - OUT-SHUFFLE");

        int choice = scanner.nextInt();
        boolean quit = false;
        do {
            System.out.println("Choose an Option");
            switch (choice) {
                case 1:
                    System.out.println("
1 - FIND
");
                    //Deck.findTop();
                    break;
                case 2:
                    System.out.println("
2 - IN-SHUFFLE
");
                    // call method
                    break;
                case 3:
                    System.out.println("
3 - OUT-SHUFFLE
");
                    // call method
                    break;
                default:
                    System.out.println("
Invalid Option");
                    break;
            }
        }
        while (!quit);

        return choice;
    }

}

我不知道如何才能阻止它不断重复.

I'm not sure how I can stop it from constantly repeating.

推荐答案

试试这个.您只需要将退出移出循环并将选项和用户选择带入循环.

try this. You just have to move quit out of loop and bring in opions and userchoice into loop.

import java.util.Scanner;
public class Switchh {

static boolean quit = false;

public static void main(String[] args) {
    int userChoice;
    userChoice = menu();
}

private static int menu() {
    Scanner scanner = new Scanner(System.in);
    int choice;
    do {

        System.out.println("Choose an Option");
        System.out.println("1 - FIND");
        System.out.println("2 - IN-SHUFFLE");
        System.out.println("3 - OUT-SHUFFLE");
        choice = scanner.nextInt();
        System.out.println("Choose an Option");
        switch (choice) {
            case 1:
                System.out.println("
1 - FIND
");
                //Deck.findTop();
                break;
            case 2:
                System.out.println("
2 - IN-SHUFFLE
");
                // call method
                break;
            case 3:
                System.out.println("
3 - OUT-SHUFFLE
");
                // call method
                break;
            default:
                System.out.println("
Invalid Option");
                quit = true;
                break;
        }
    }
    while (!quit);

    return choice;
}

}

相关文章