java - 循环遍历 switch 语句

标签 java while-loop switch-statement

所以我正在编写一个基于菜单的程序,但我陷入了一个部分。这是我的代码:

public static void main(String [] args) throws FileNotFoundException {
    switch (menu()) {
        case 1:
            System.out.println("Stub 1");
            menu();
            break;
        case 2:
            System.out.println("Stub 2");
            menu();
            break;
        case 3:
            System.out.println("Stub 3");
            menu();
            break;
        case 4:
            System.out.println("Program Terminated");
            break;

    }

}

public static int menu() {
    System.out.println("Choose a task number from the following: ");
    System.out.println("\t1. - See histogram of name's popularity");
    System.out.println("\t2. - Compare two names in a specific decade");
    System.out.println("\t3. - Show what name had a specific rank for a certain decade");
    System.out.println("\t4. - Exit program");
    int opt = 0;
    int option = getInt(input,"Enter number (1-4): ", 1, 4);
    if (option == 1) {
        opt = 1;
    }
    else if (option == 2) {
        opt = 2;
    }
    else if (option == 3) {
        opt = 3;
    } 
    else {
        opt = 4;
    }
    return opt;
}

我的问题是,按下选项后如何使菜单“重置”。例如,我选择 1,程序执行该操作,完成后,它会再次显示选项菜单,直到我按 4 终止它。

我的代码中的 getInt 方法仅返回 1 到 4 之间的 int。

最佳答案

一个简单的选择是声明一个 boolean 变量并将switch包装在一个while循环中,例如

Boolean quit = false;
while (!quit)        //or do-while
{
    int opt = menu();
    switch(opt)
    {
        //other cases...
        case 4:
            quit = true;
    }
}

我不确定为什么你在每种情况下都调用菜单。

关于java - 循环遍历 switch 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27073299/

相关文章:

java - 鼠标右键事件

java - Digital Persona One Touch 中的验证 Java API 可以在没有 RTE 的情况下运行吗?

java - 需要修复时间转换为 hh :mm

java - 如何在 while 循环中正确使用 switch 语句

objective-c - 代替 switch-case,更有效地选择字符串

swift - 在 observeValueForKeyPath 中使用开关

java - 如何用动态变化的简单数组创建多维数组?

java - Java 上 0.1 到 2 的奇怪循环

php - Break While 循环添加 "last"到 <div>

java - 方法流程+开关