我正在尝试读取一个用于开关案例选项的数字,但我遇到了异常。我将尝试在代码中更好地解释问题:
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)
这样的东西,而缓冲区只是开始写得像疯了一样。
答案 0 :(得分:1)
如果您失败,您可以在 编辑:当失败时,您可以使用Scanner
内创建catch
的新实例,以获得输入。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();
}
}