JAVA:菜单无限循环

时间:2013-12-22 14:53:44

标签: java infinite-loop

这是我之前提出的一个问题的后续问题,该问题确实得到了应该解决我的问题的答案,但不幸的是没有。我的程序读入文本文件并在为用户提供许多选项之前组织数据。当程序到达这一点时,我希望用户能够选择执行操作的选项,但随后将用户返回到起点以便能够执行更多操作。这是我最喜欢的答案(感谢Octopus),目前正在尝试实施。

//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\" or \"3\"");
        if(scanchoice.hasNextInt())
        choiceentry = scanchoice.nextInt();

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

我认为,程序最初应进入循环,允许用户输入选择,然后返回“输入值”。但是,程序不会返回,并在一次操作后终止。如何防止这种情况继续无限运行?

提前致谢!

5 个答案:

答案 0 :(得分:2)

当前的while循环用于获取有效输入 - 不要更改它。

您需要将此代码包装在另一个while循环中,循环直到输入sentinal值。

while (!isSentinalValue) {
  while (inputNotValid) {
    // get valid input
  }
}

修改

更具体地说,在伪代码中:

while (!isSentinalValue) {
  input = invalidValue
  while (inputNotValid) {
     getInput
  }
  use input to do menu things
}

所以我不会在内部循环内部使用switch块,因为该循环只关注确保输入的输入是有效的。切换块在内部循环之外,并确保设置sentintal值,允许用户在适当的时候逃离外环。

答案 1 :(得分:1)

您的while(choiceentry < 1 || choiceentry > 3)条件错误。如果你想让它循环,那么你必须在1到3之间。

因此,这也意味着您必须更改您的choiceentry初始化值。这会奏效。

int choiceentry = 1

while(choiceentry >=1 && choiceentry <= 3){

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

   ....
}

答案 2 :(得分:0)

只有当choiceentry小于1或大于3时,才会运行循环。只要用户输入其中一个值,循环就会退出。

学习使用调试器。

答案 3 :(得分:0)

在切换

后放置以下代码
if(choiceentry == 4){
break;
}

现在,当您输入4时,它将被终止,您可以使用除4之外的任何值

答案 4 :(得分:0)

仅在用户想要退出时使用break(在choiceentry = 0时说)。您可以使用“继续”使循环无限。示例代码仅供参考

    int choiceentry = 1; // can set any int value except 0 (exit code is 0 for this example)
    Scanner scanchoice = null;

    while (choiceentry != 0) {

        System.out.println("Enter \"1\", \"2\" or \"3\" ..Press 0 to quit");
        scanchoice = new Scanner(System.in);

        if (scanchoice.hasNextInt())
            choiceentry = scanchoice.nextInt();
        // System.out.println("choiceentry=" + choiceentry);

        switch (choiceentry) {

        case 0:

        {
            System.out.println("Bye Bye");
            break;

        }
        case 1:

        {
            System.out.println("In Case 1");
            continue;

        }

        case 2: {
            System.out.println("In Case 2");
            continue;

        }
        case 3: {
            System.out.println("In Case 3");
            continue;

        }
        }
    }