Scanner.reset()不起作用 [英] Scanner.reset() doesn't work

查看:55
本文介绍了Scanner.reset()不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码应该从用户那里得到一个整数,然后完成程序.如果用户输入的号码无效,则会再次询问用户.

This piece of code is supposed to get an integer number from user and then finish the program. If the user inputs an invalid number, it asks user again.

捕获到异常后,它使用 Scanner.reset()重置扫描仪,但是不起作用.并重新引发先前的异常.

After catching exception, it uses Scanner.reset() to reset the scanner, but it doesn't work. and it re-throws previous exception.

Scanner in = new Scanner(System.in);
while (true) {
    try {
        System.out.print("Enter an integer number: ");
        long i = in.nextLong();
        System.out.print("Thanks, you entered: ");
        System.out.println(i);
        break;
    } catch (InputMismatchException ex) {
        System.out.println("Error in your input");
        in.reset(); // <----------------------------- [The reset is here]
    }
}

我认为 Scanner.reset()将重置所有内容,并忘记了异常.我把它放在询问用户新的输入之前.

I thought Scanner.reset() will reset everything and forget the exception. I put it before asking the user for a new input.

如果我弄错了,正确的方法是什么?

If I get the point wrong, what is the right way?

推荐答案

您误解了 reset 方法的目的:它可以重置与扫描仪关联的元数据"-它的空白,分隔符等.它不会更改其输入状态,因此无法实现您想要的功能.

You misunderstood the purpose of the reset method: it is there to reset the "metadata" associated with the scanner - its whitespace, delimiter characters, and so on. It does not change the state of its input, so it would not achieve what you are looking for.

您需要的是 next()的调用,该调用将从 Scanner 中读取并丢弃任何 String :

What you need is a call of next(), which reads and discards any String from the Scanner:

try {
    System.out.print("Enter an integer number: ");
    long i = in.nextLong();
    System.out.print("Thanks, you entered: ");
    System.out.println(i);
    break;
} catch (InputMismatchException ex) {
    System.out.println("Error in your input");
    in.next(); // Read and discard whatever string the user has entered
}

依靠异常来捕获异常情况是可以的,但是解决同一问题的更好方法是在调用 next ... 之前使用 has ... 方法.>方法,例如:

Relying upon exceptions to catch exceptional situations is OK, but an even better approach to the same issue would be using has... methods before calling the next... methods, like this:

System.out.print("Enter an integer number: ");
if (!in.hasNextLong()) {
    in.next();
    continue;
}
long i = in.nextLong();
System.out.print("Thanks, you entered: ");
System.out.println(i);
break;

这篇关于Scanner.reset()不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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