JAVA:创建菜单循环

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20681616/
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-13 03:34:21  来源:igfitidea点击:

JAVA: Creating a Menu Loop

javainfinite-loopnested-loops

提问by user2941526

My program contains a few options that the user can select via the input of a number which allows them to complete a specific task. Currently, my code is set up with if and else if loops to complete task if a certain number of input. However, at the minute the program terminates after one task. I want the user to be able to input another number to complete another task. I have tried surrounding the code with a while loop and an exit option to allow the user to escape the loop and end the program, but this is not working and results in a "java.util.NoSuchElementException". The program works fine without the while loop.

我的程序包含一些选项,用户可以通过输入数字来选择这些选项,以便他们完成特定任务。目前,我的代码设置了 if 和 else if 循环以在输入一定数量时完成任务。但是,程序在完成一项任务后立即终止。我希望用户能够输入另一个数字来完成另一个任务。我尝试使用 while 循环和退出选项来包围代码,以允许用户退出循环并结束程序,但这不起作用并导致“java.util.NoSuchElementException”。该程序在没有 while 循环的情况下运行良好。

This is an example of the current code which hopefully conveys what I mean:

这是当前代码的一个示例,希望能传达我的意思:

System.out.println("Enter one of the following commands:");
System.out.println("1 - something..");
System.out.println("2 - something else..");
System.out.println("3 - exit");
Scanner scanchoice = new Scanner(System.in);
System.out.println();
System.out.println("Enter \"1\", \"2\" or \"3\"");
int choiceentry = scanchoice.nextInt();

while (choiceentry != 3) {

    if (choiceentry < 1 || choiceentry > 3) {

        System.out.println("Enter \"1\", \"2\", \"3\" or \"4\"");
        choiceentry = scanchoice.nextInt();

    }

    else if(choiceentry == 1) {
        // ..do something
    }
    else if(choiceentry == 2) {
        //..something else
    }
    else if(choiceentry == 3) {
        //...exit program
    }

}   

So I want to get into this loop, and only exit to terminate the program. I'm hoping that the while loop would take the user back to a menu, allowing you to select another option, however this is not working. What is wrong with this code? And how can I implement this idea?

所以我想进入这个循环,只有退出才能终止程序。我希望 while 循环会将用户带回菜单,允许您选择另一个选项,但这不起作用。这段代码有什么问题?我怎样才能实现这个想法?

Thanks in advance!

提前致谢!

回答by Keerthivasan

Use Scanner#hasNextInt()before you call Scanner.nextInt()to get rid of the NoSuchElementException

Scanner#hasNextInt()在您打电话之前使用Scanner.nextInt()以摆脱NoSuchElementException

if(scanchoice.hasNextInt())
choiceentry = scanchoice.nextInt();

hasNextInt()returns true only if the next token is a valid int

hasNextInt()仅当下一个标记是有效的 int 时才返回 true

You can do like this

你可以这样做

    //set choiceentry to -1, this will make it to enter while loop
     int choiceentry = -1

    while(choiceentry < 1 || choiceentry > 3){

            System.out.println("Enter \"1\", \"2\", \"3\" or \"4\"");
            if(scanchoice.hasNextInt())
            choiceentry = scanchoice.nextInt();

    }

     switch(choiceentry){
        case 1:
           //do logic
           break;
        case 2:
           //do logic
           break;
        case 3:
           //do logic
           break;
   }

I have changed it to use switch statements, since they come handy in getting input data

我已将其更改为使用 switch 语句,因为它们在获取输入数据时很方便

回答by RamonBoza

You are only asking the user to pick another menu item if choice is < 1or > 3

如果选择是< 1或,您只是要求用户选择另一个菜单项> 3

you have to set this code in an elsestatement`:

您必须在else语句中设置此代码:

while (choiceentry != 3) {
    else if(choiceentry == 1) {
        // ..do something
    }
    else if(choiceentry == 2) {
        //..something else
    }
    else if(choiceentry == 3) {
        //...exit program
    }
    else{

        System.out.println("Enter \"1\", \"2\", \"3\" or \"4\"");
        choiceentry = scanchoice.nextInt();

    }

}   

回答by PakkuDon

If you want your program to continue prompting the user to select a task you'll need to move that prompt as well as your nextInt()call to somewhere inside your loop yet outside of an if statement so that it will always be invoked on each iteration.

如果您希望您的程序继续提示用户选择一个任务,您需要将该提示以及您的nextInt()调用移动到循环内部但在 if 语句之外的某个位置,以便在每次迭代时始终调用它。

As Mr Phi suggested in the comments, a switch statement would be a better alternative to your current if-else structure. It'll make your code cleaner to read and a default case is pretty nice for catching unexpected values.

正如 Phi 先生在评论中所建议的那样,switch 语句将是您当前 if-else 结构的更好替代方案。它将使您的代码更清晰易读,并且默认情况非常适合捕获意外值。

I'd also add that a do-while might be more suitable for this task. This way you won't need to code your prompt for a choice twice.

我还要补充一点,do-while 可能更适合这项任务。这样您就不需要为选择的提示编写两次代码。

int choiceentry;

do {
    System.out.println("Enter \"1\", \"2\" or \"3\"");
    choiceentry = scanchoice.nextInt();

    switch (choiceentry)
    {
        case 1:
            // do something
            break;
        case 2: 
            // ..something else
            break;
        case 3: 
            // .. exit program
            break;
        default:
            System.out.println("Choice must be a value between 1 and 3.");
    }   
} while (choiceentry != 3);