使用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
- 没有在路径DexPathList上找到类
- javax.activation.UnsupportedDataTypeException:没有MIME类型multipart / mixed的对象DCH; 边界
- 有效URL的java.io.FileNotFoundException
- Java:BufferedReader的readLine()中的IOEXceptions是什么?
- 使用lsof对“打开的文件太多”进行故障排除
- java.util.zip.ZipFile.close()什么时候抛出IOException?
- 无法通过代理隧道。 代理返回HTTP / 1.1 503服务不可用
- Java编译器抱怨未报告的IOException
- IOException – 使用FileOutputStream拒绝访问