boolean valid = false;
System.out.println("What block are you gathering? (use minecraft block ids)");
while(valid == false){
try{
block = input.nextInt();
valid = true;
}
catch(InputMismatchException exception){
System.out.println("What block are you gathering? (use minecraft block ids)");
valid = false;
}
}
解决方法:
nextInt()不会消耗无效输入,因此它会一遍又一遍地尝试读取相同的无效值.要解决此问题,您需要通过调用接受任何值的next()或nextLine()来显式使用它.
顺便说一句,为了使您的代码更清晰并避免像创建异常这样的昂贵操作,您应该使用像hasNextInt()这样的方法.
以下是组织代码的方法
System.out.println("What block are you gathering? (use minecraft block ids)");
while(!input.hasNextInt()){
input.nextLine();// consume invalid values until end of line,
// use next() if you want to consume them one by one.
System.out.println("That is not integer. Please try again");
}
//here we are sure that next element will be int, so lets read it
block = input.nextInt();
标签:java,while-loop,loops
来源: https://codeday.me/bug/20191003/1848977.html