使用Scanner读取输入会导致Java中的无限循环

在我的程序中,我试图让用户在1-3之间输入一个int,然后根据他们键入的内容做一些事情。 如果它不是数字或不是其中一个选项,那么它将允许它们重新输入有效选项。

我遇到的问题是我无法集思广益,如何不让它无限循环,只是让它们在控制台告诉他们输入无效输入后输入一个数字。

int i = 0; while (i < 1) { try { int level = scan.nextInt(); i+=1; if (level == 1) { System.out.println("You selected level 1!"); //Start the game } else if (level == 2) { System.out.println("You selected level 2!"); //Start the game } else if (level == 3) { System.out.println("You selected level 3!"); //Start the game } else { System.out.println("That's not an option!"); i-=1; } } catch(InputMismatchException input) { System.out.println("That's not an option!"); i-=1; } } 

输入无效输入时,需要清除它。 触发输入exception时添加scan.next()以便使用next()清除它:

  catch(InputMismatchException input) { System.out.println("That's not an option!"); scan.next(); i-=1; } 

不是你期待的答案,但是:重构这段代码。 记住java的基础知识,其中每个function位都有自己的方法。 因此,使用一个读取输入的方法,并返回所选的级别(如果没有则返回-1):

 int readInput() { // your code here, returning either the level or -1 on bad input } 

然后调用它为您的读取循环:

 int selected; do { selected = readInput(); } while(selected < 1); 

你最好写这样的代码:

 while(true){ try{ int level = scan.nextInt(); if(level==1){ System.out.println("You selected level 1!"); break; }else if(level==2){ System.out.println("You selected level 2!"); break; }else if(level==3){ System.out.println("You selected level 3!"); break; }else{ System.out.println("That's not an option!"); continue; } }catch(InputMismatchException input){ System.out.println("That's not an option!"); continue; } } 

continue将立即恢复在顶部执行循环,并且break将立即跳转到while的结束括号} 。 这消除了使用i计数器变量,这对代码完全没用。 此外,此代码永远不会无限期运行,除非用户无限期地输入不正确的值!

希望这有帮助,祝你好运!

您可以以更简单的方式继续。 3个有效案例非常相似,可以视为一个,游戏只能在循环后启动一次,因为我们知道一旦循环退出, level就有一个有效值。

 boolean valid = false; int level; do { try { level = scan.nextInt(); valid = 1 <= level && level <= 3; if (valid) { System.out.println(String.format("You selected level %d !",level)); } else { System.out.println("That's not an option!"); } } catch(InputMismatchException input) { scan.next(); System.out.println("That's not an option!"); } } while (!valid); // start the game