如何使用Scanner处理由无效输入(InputMismatchException)引起的无限循环 [英] How to handle infinite loop caused by invalid input (InputMismatchException) using Scanner

查看:142
本文介绍了如何使用Scanner处理由无效输入(InputMismatchException)引起的无限循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我对这段代码感到困惑:

So, I'm getting stuck with this piece of code:

import java.util.InputMismatchException;
import java.util.Scanner;

public class ConsoleReader {

    Scanner reader;

    public ConsoleReader() {
        reader = new Scanner(System.in);
        //reader.useDelimiter(System.getProperty("line.separator"));
    }

    public int readInt(String msg) {
        int num = 0;
        boolean loop = true;

        while (loop) {
            try {
                System.out.println(msg);
                num = reader.nextInt();

                loop = false;
            } catch (InputMismatchException e) {
                System.out.println("Invalid value!");
            } 
        }
        return num;
    }
}

这是我的输出:


插入整数:

无效值!

插入一个整数:

无效值!

...

Insert a integer number:
Invalid value!
Insert a integer number:
Invalid value!
...


推荐答案

按照扫描仪 javadoc


当扫描程序抛出
InputMismatchException时,扫描程序
将不会传递导致
异常的令牌,因此可以通过其他
方法检索或跳过

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.

这意味着如果下一个token不是 int ,它会抛出 InputMismatchException ,但令牌仍然存在。因此,在循环的下一次迭代中, reader.nextInt()再次读取相同的标记并再次抛出异常。你需要的是用它。在 catch 中添加 reader.next()以使用该令牌,该令牌无效且需要被丢弃。

That means that if the next token is not an int, it throws the InputMismatchException, but the token stays there. So on the next iteration of the loop, reader.nextInt() reads the same token again and throws the exception again. What you need is to use it up. Add a reader.next() inside your catch to consume the token, which is invalid and needs to be discarded.

...
} catch (InputMismatchException e) {
    System.out.println("Invalid value!");
    reader.next(); // this consumes the invalid token
} 

这篇关于如何使用Scanner处理由无效输入(InputMismatchException)引起的无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆