简体   繁体   English

JAVA:创建菜单循环

[英]JAVA: Creating a Menu Loop

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. 当前,我的代码设置有if和else if,如果有一定数量的输入,则if循环完成任务。 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". 我尝试用while循环和退出选项将代码括起来,以允许用户逃脱循环并结束程序,但这不起作用,并导致“ java.util.NoSuchElementException”。 The program works fine without the while loop. 程序运行良好,没有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. 我希望while循环可以将用户带回到菜单,允许您选择另一个选项,但这不起作用。 What is wrong with this code? 此代码有什么问题? And how can I implement this idea? 我该如何实现这个想法?

Thanks in advance! 提前致谢!

Use Scanner#hasNextInt() before you call Scanner.nextInt() to get rid of the NoSuchElementException 在调用Scanner.nextInt()摆脱NoSuchElementException之前使用Scanner#hasNextInt()

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语句,因为它们在获取输入数据时非常方便

You are only asking the user to pick another menu item if choice is < 1 or > 3 您仅在选择< 1> 3要求用户选择另一个菜单项

you have to set this code in an else statement`: 您必须在else语句中设置此代码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();

    }

}   

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. 正如Phi先生在评论中所建议的那样,switch语句将是您当前的if-else结构的更好替代方案。 It'll make your code cleaner to read and a default case is pretty nice for catching unexpected values. 这将使您的代码更清晰可读,并且默认情况下非常适合捕获意外的值。

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. 这样,您就不需要为两次选择编码您的提示。

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM