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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32289035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:17:46  来源:igfitidea点击:

How to add option to exit from switch case in Java

java

提问by Abhijit Kumbhar

I am creating a menu based program in java using switch case. here are 4 cases:

我正在使用 switch case 在 java 中创建一个基于菜单的程序。这里有4种情况:

  1. add record
  2. delete record
  3. update record
  4. Exit
  1. 添加记录
  2. 删除记录
  3. 更新记录
  4. 出口

I added break after each case but, what I want to do is to terminate the program when user enter case no 4 so what to do in this case ?

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

采纳答案by ajb

Please don't use System.exit. It's like trying to use a chainsaw to slice a tomato. It's a blunt tool that might be useful for emergency situations, but not for normal situations like you're trying to write.

请不要使用System.exit。这就像试图用电锯切西红柿一样。这是一个生硬的工具,可能对紧急情况有用,但不适用于像您正在尝试编写的正常情况。

There are a couple better approaches: (1) If you put your loop in a method, where the method's only purpose is to read the user's input and perform the desired functions, you can returnfrom that method:

有几种更好的方法:(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;
        }
    }
}

Now, whatever program calls mainMenu()has an opportunity to do some cleanup, print a "goodbye" message, ask the user if they want to back up their files before exiting, etc. You can't do that with System.exit.

现在,任何程序调用mainMenu()都有机会进行一些清理、打印“再见”消息、询问用户是否要在退出前备份他们的文件等。你不能用System.exit.

Another mechanism, besides return, is to use breakto exit the loop. Since breakalso breaks out of a switch, you'll need a loop label:

除了 之外return,另一种机制是break用于退出循环。由于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
}

Or (as Riddhesh Sanghvi suggested) you can put a condition in the whileloop instead of breaking out of it. His answer used a condition based on the option; another idiom I've used a lot is to set up a booleanfor the purpose:

或者(正如 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
}

Or:

或者:

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

So you have a lot of options, all better than System.exit.

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

回答by Shubham Chaurasia

return OR System.exit(ExitCode) if you want to exit directly.

如果您想直接退出,则返回 OR System.exit(ExitCode)。

回答by Bruno Caceiro

You can use System.exit()for this purpose.

您可以System.exit()为此目的使用。

System.exit(int status)

Terminates the currently running Java Virtual Machine.

System.exit(int 状态)

终止当前运行的 Java 虚拟机。

回答by Wololo

In case no 4, add:

如果没有 4,请添加:

System.exit(int status);

Usually, status >= 0indicates that the program terminated correctly and status < 0indicates an abnormal termination. I think you should use:

通常,status >= 0表示程序正确终止,status < 0表示异常终止。我认为你应该使用:

System.exit(0);

statusserves as errorCode. You can assign whatever value you want. If your program contains many exit points, you can assign different errorCodes to them. You can return the errorCode to the environment which called the application. Through this errorCode, you can trace which System.exit() caused the program to terminate.

status作为错误代码。您可以分配任何您想要的值。如果您的程序包含许多退出点,您可以为它们分配不同的错误代码。您可以将 errorCode 返回给调用应用程序的环境。通过此错误代码,您可以追踪是哪个 System.exit() 导致程序终止。

回答by burglarhobbit

Your particular casein your switchstatement would be:

caseswitch声明中的具体内容是:

case 4: System.exit(0);

回答by Riddhesh Sanghvi

If you do not wish to choose either returnor System.exit(ExitCode)then put the termination condition in while loop as shown below.
Why to put while(true)and then put returnor System.exitinsteadexploit the boolean check of the while loop to exit it.

如果您不想选择两者之一returnSystem.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
}

回答by Radhesh Khanna

Whenever You want to Exit out of the Switch case it is always better to use a do-while loop because that gives the user an advantage of running the Program again if he wants to update, delete or add Multiple records as in your Program

每当您想退出 Switch 案例时,最好使用 do-while 循环,因为如果他想更新、删除或添加多条记录,就像在您的程序中一样,这使用户可以再次运行程序

class record{
public static void main(String args[]){
do
{
System.out.Println("Enter Choice ");
Scanner sc = new Scanner(System.in);
int choice = sc.nextInt();
switch(option){
case 1:{
//Code for Adding the Records
break; 
}
case 2:{
//Code for deleting the Records
break;
}
case 3:{
//Code for Updating the Records 
break;
}
case 4:{
break; 
      }
   }
}
while(choice!=4);
    }
}

Wherever you want to add the Code for adding,deleting and updating the records you can call the Methods also which are defined outside the Switch Case and the Program should run just fine

无论您想在何处添加用于添加、删除和更新记录的代码,您都可以调用在 Switch Case 之外定义的方法,并且程序应该可以正常运行

回答by RJSoni13

float ans;

浮动 ans;

    switch(operator)
    {
        case '+':
            ans = no1 + no2;
            break;

        case '-':
            ans = no1 - no2;
            break;

        case '*':
              ans = no1 * no2;
            break;

        case '/':
              ans = no1 / no2;
            break;
    case '0':
    System.exit(0);

        default:
            System.out.printf("EERRRoOOOORRR(^!^)");
            return;
    }