首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >inputmismatchexception:进入无限循环?

inputmismatchexception:进入无限循环?
EN

Stack Overflow用户
提问于 2016-05-18 15:22:03
回答 3查看 219关注 0票数 1

我面对的是java.util.InputMismatchException;

我捕获了InputMismatchException,但我不明白为什么它在接受第一个错误的输入后会进入无限循环,并且输出是这样的:

代码语言:javascript
复制
enter two integers 
exception caught

这会不断重复

代码语言:javascript
复制
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");
        }
    }
}
EN

回答 3

Stack Overflow用户

发布于 2016-05-18 15:39:41

您需要清除缓冲区,以便在抛出异常后它不会对nextInt()无效。添加一个finally块并在其中调用sc.nextLine()

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2016-05-18 15:24:11

如果您按enter键,则还需要使用此字符

代码语言:javascript
复制
int a = sc.nextInt();
int b = sc.nextInt(); 
sc.nextLine ();

然后你就可以进入

代码语言:javascript
复制
2 3 <CR>
票数 0
EN

Stack Overflow用户

发布于 2016-05-18 15:29:23

在您的代码中,您捕获了InputMisMatchException,并且您只是打印了一条消息,这将导致再次转到while循环。

代码语言:javascript
复制
        int a = sc.nextInt(); 
        int b = sc.nextInt();

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/37292789

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档