Scanner.reset()不起作用

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

捕获exception后,它使用Scanner.reset()来重置扫描程序,但它不起作用。 并重新抛出先前的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()会重置所有内容并忘记exception。 我在询问用户输入新内容之前先说了。

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

您误解了reset方法的目的:它可以重置与扫描程序关联的“元数据” – 它的空格,分隔符等。 它不会改变其输入的状态,因此无法实现您的目标。

你需要的是next()的调用,它从Scanner读取并丢弃任何String

 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 } 

依赖exception来捕获exception情况是可以的,但是在调用next...方法之前使用has...方法更好的方法是使用has... next...方法,如下所示:

 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; 

Per Scanner.reset()javadoc ,该方法仅“重置”语言环境,基数和分隔符设置。 它对已读取的数据没有任何作用。