1

为什么我在输入非数字令牌时会出现无限循环?

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);
            }     
        }            
    }
}
4

1 回答 1

2

您实际上是在问“为什么当我输入非整数输入时我的代码会运行到无限循环”。

好吧,您需要调用in.next()catch子句来解决这个问题。为什么?请参阅Scanner文档:

当扫描器抛出一个InputMismatchException时,扫描器将不会传递导致异常的令牌,以便可以通过其他方法检索或跳过它。

于 2015-05-10T10:20:27.577 回答