【问题标题】:inputmismatchexception: entering into infinite loop? [duplicate]inputmismatchexception:进入无限循环? [复制]
【发布时间】:2016-05-18 07:22:03
【问题描述】:

我面对的是java.util.InputMismatchException;

我捕捉到 InputMismatchException 但我不明白为什么它在第一次输入错误后进入无限循环并且输出如下:

enter two integers 
exception caught

这样重复

public static void main(String[] args) {
    Scanner sc = new Scanner(System.in);
    int flag = 0;
    while (flag != 1) {
        try {
            System.out.println("enter two integers");
            int a = sc.nextInt();
            int b = sc.nextInt();
            int result = a + b;
            flag = 1;
            System.out.println("ans is" + result);
        } catch (NumberFormatException e) {
            System.out.println("exception caught");
        } catch (InputMismatchException e) {
            System.out.println("exception caught");
        }
    }
}

【问题讨论】:

    标签: java


    【解决方案1】:

    你需要清空缓冲区,这样在抛出异常后它不会对nextInt()无效。添加finally 块并在其中调用sc.nextLine()

    while (flag != 1) {
        try {
            System.out.println("enter two integers");
            int a = sc.nextInt();
            int b = sc.nextInt();
            int result = a + b;
            flag = 1;
            System.out.println("ans is" + result);
    
        } catch (NumberFormatException e) {
            System.out.println("exception caught");
        } catch (InputMismatchException e) {
            System.out.println("exception caught");
        } finally {  //Add this here
            sc.nextLine();
        }
    }
    

    工作示例:https://ideone.com/57KtFw

    【讨论】:

    • 虽然这对1 2之类的数据有效,但对于1 2 3之类的数据将失败,因为nextLine()被放置在finally中,这意味着它会消耗整行即使出现异常不会被抛出,因此它也会消耗3,这可能是应用程序后期的有效输入。最好在 catch 块中处理每个异常,finally 部分用于强制执行的任务,无论是否抛出异常。
    【解决方案2】:

    如果你按下回车键,你也需要消耗这个字符

    int a = sc.nextInt();
    int b = sc.nextInt(); 
    sc.nextLine ();
    

    然后就可以进入了

    2 3 <CR>
    

    【讨论】:

    • @Berger 是的,我不太确定 OP 希望如何输入他的数据。
    【解决方案3】:

    在您的代码中,您正在捕获 InputMisMatchException,而您只是在打印一条消息,这将导致再次进入您的 while 循环。

            int a = sc.nextInt(); 
            int b = sc.nextInt();
    

    当其中任何一行抛出异常时,您的flag=1 将不会被设置,您将处于无限循环中。更正您的异常处理并跳出循环或通过将扫描仪输入读取为字符串来清除它。

    【讨论】:

      猜你喜欢
      • 2021-12-18
      • 2018-01-16
      • 1970-01-01
      • 2012-09-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多