java - 为什么我的异常处理错误会导致无限循环?

标签 java exception

我的异常处理遇到了麻烦。如果我输入一个数字,程序运行正常,但如果输入一个字符,则创建一个无限循环。

boolean ask= true;
    while(ask)
    {
        ask = false;
        try 
        {
            System.out.println("What is the age?");
            int age = input.nextInt();  
            setAge(age);
        }catch(InputMismatchException e) {
            System.out.println("Invalid input!");
            ask = true;
        }
    }//end while

最佳答案

尝试下面的代码:

      boolean ask= false;
        while(!ask)
        {
           try
           {
               System.out.println("What is the age?");
               int age = input.nextInt();//does not read the newline character in your input created by hitting "Enter,"
               setAge(age);
               ask = true;
           }catch(InputMismatchException e) {
               System.out.println("Invalid input!");
               input.nextLine();//consumes the \n character
           }
        }//end while

关于java - 为什么我的异常处理错误会导致无限循环?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54848963/

相关文章:

java - 更新类中的类

java.lang.RuntimeException : Performing stop of activity that is not resumed:

java - java中十六进制字符串到整数解析异常处理

Java:异常

java - 有些测试用例没有运行,但有些是概率测试

java - 在 hibernate 中包含 log4j 属性文件以显示带有值而不是问号的查询

java - 如何将 JLabel[] 添加到 JTable?

c++ - RAII 的有用性无一异常(exception)

c++ - 是什么导致我在 Qt 中的第一次机会(堆栈溢出)异常?

exception - 通过 JMX 访问 Apache ActiveMQ 抛出异常