为什么当我输入非数字标记时会出现无限循环?
public class ExceptionHandling {
static int i;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
boolean b=true;
Scanner in=new Scanner(System.in);
while (b ==true) {
try{
i=in.nextInt();
b=false;
// System.out.println("not executrd bcoz above exception");
}
catch(InputMismatchException e){
System.out.println(i);
}
}
}
}
最佳答案
您实际上是在问“为什么当我输入非整数输入时我的代码会运行到无限循环”。
那么,您需要在 catch
子句中调用 in.next()
来解决这个问题。为什么?请参阅Scanner
文档:
When a scanner throws an
InputMismatchException
, the scanner will not pass the token that caused the exception, so that it may be retrieved or skipped via some other method.
关于java - 为什么当我输入非整数输入时我的代码会运行到无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30150170/