本文介绍了如何使用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;
    }
}

这是我的输出:


推荐答案

按照扫描仪:

这意味着如果下一个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)引起的无限循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 21:51