java - 为什么当我输入非整数输入时我的代码会运行到无限循环?

标签 java java.util.scanner inputmismatchexception

为什么当我输入非数字标记时会出现无限循环?

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/

相关文章:

Java BitSets 写入文件

Java读取txt文件到hashmap,按 ":"分割

Java:限制字符串中的字符

java - 无法捕获 InputMismatchException

java - java 中的 nextFloat 问题

c# - 具有可变数量参数的函数

java - 向 Swing gui 添加可以支持特殊字符的控制台输出

java - 在空白处分割文本文件

java - 如何处理这个InputMismatchException?

java - 如何使用 Kryo 序列化 Joda-Time 的 LocalDate