如何在Java中添加退出switch case的选项

Abh*_*har -1 java

我正在使用switch case在java中创建一个基于菜单的程序.这里有4个案例:

  1. 添加记录
  2. 删除记录
  3. 更新记录
  4. 出口

我在每个案例之后添加了break但是,我想要做的是在用户输入案例4时终止程序,那么在这种情况下该怎么办?

ajb*_*ajb 5

请不要使用System.exit.这就像试图用电锯切番茄一样.这是一个生硬的工具,可能对紧急情况很有用,但不适合你正在尝试编写的正常情况.

有几种更好的方法:(1)如果将循环放在一个方法中,方法的唯一目的是读取用户的输入并执行所需的函数,您可以return从该方法:

private static void mainMenu() {
    while(true) {
        char option = getOptionFromUser();
        switch(option) {
            case '1':
                addRecord();
                break;
            case '2':
                deleteRecord();
                break;
            case '3':
                updateRecord();
                break;
            case '4':
                return;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,无论程序调用mainMenu()有没有机会进行一些清理,打印"再见"消息,询问用户是否要在退出之前备份文件,等等.你不能这样做System.exit.

另外,另一种机制returnbreak用于退出循环.由于break也会突破a switch,你需要一个循环标签:

private static void mainMenu() {
    menuLoop:
    while(true) {
        char option = getOptionFromUser();
        switch(option) {
            ... as above
            case '4':
                break menuLoop;
        }
    }
    ... will go here when user types '4', you can do other stuff if desired
}
Run Code Online (Sandbox Code Playgroud)

或者(正如Riddhesh Sanghvi建议的那样)你可以在while循环中放入一个条件而不是破坏它.他的答案使用的条件是基于option; 我用过的另一个成语是boolean为了这个目的而建立一个:

private static void mainMenu() {
    boolean askForAnother = true;
    while(askForAnother) {
        char option = getOptionFromUser();
        switch(option) {
            ... as above
            case '4':
               askForAnother = false;
        }
    }
    ... will go here when user types '4', you can do other stuff if desired
}
Run Code Online (Sandbox Code Playgroud)

要么:

private static void mainMenu() {
    boolean done = false;
    do {
        char option = getOptionFromUser();
        switch(option) {
            ... as above
            case '4':
                done = true;
        }
    } while (!done);
}
Run Code Online (Sandbox Code Playgroud)

所以你有很多选择,都比这更好System.exit.


Rid*_*hvi 5

如果您不想选择任何一个,return或者System.exit(ExitCode)将终止条件置于while循环中,如下所示.
为什么放置while(true)然后放入returnSystem.exit 改为 利用while循环的布尔检查来退出它.

private static void mainMenu() {
    int option=0;//initializing it so that it enters the while loop for the 1st time 
    while(option!=4){
        option = getOptionFromUser();
        switch(option) {
            case 1:
                addRecord();
                break;
            case 2:
                deleteRecord();
                break;
            case 3:
                updateRecord();
                break;
            case 4:
                System.out.print("While Loop Terminated");
                break;
        }
    }
    // when user enters 4,
    //Will execute stuff(here the print statement) of case 4 & then
    //... will come here you can do other stuff if desired
}
Run Code Online (Sandbox Code Playgroud)