我正在尝试读取开关盒选项的数字,但遇到异常。我会尝试用代码更好地解释问题:
do{
try{
loop=false;
int op=teclado.nextInt();
//I tryed a teclado.nextLine() here cause i saw in other Q but didn't work
}
catch(InputMismatchException ex){
System.out.println("Invalid character. Try again.");
loop=true;//At the catch bolck i change the loop value
}
}while(loop);//When loop is true it instantly go to the catch part over and over again and never ask for an int again
当我输入一个 int 时,它工作得很好,但异常使它重新开始。第二次,程序不要求 int (我认为它可能是一个缓冲区,我需要像 C 中的 fflush(stdin)
这样的东西),并且缓冲区开始疯狂地写入。
最佳答案
您可以从 编辑:当失败时,您可以使用catch
中创建一个新的 Scanner
实例,以便在失败时获取输入。Scanner.nextLine()
前进到换行符之后。 do...while
循环可能不适合这种情况,因为它保证至少执行一次。
一个可以帮助您更多的结构是一个简单的 while
循环。这实际上是一个 while-true-break
类型的循环,它会在有效输入时中断。
while(true) {
try {
op=teclado.nextInt();
break;
} catch(InputMismatchException ex){
System.out.println("Invalid character. Try again.");
teclado.nextLine();
}
}
关于java - java代码无限循环,Scanner对象缓冲区可能是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10360691/