使用Scanner.nextInt()与Scanner.nextLine()进行exception处理

此问题仅用于教育目的。 我从Java教科书中获取了以下代码,我很好奇为什么在catch块中使用了input.nextLine()。

我尝试在其位置使用input.nextInt()编写程序。 该程序将不再适当地捕获exception。 当我传递一个非整数值时,控制台显示熟悉的“线程中的exception…”错误消息。

当我完全删除该行代码时,控制台将无休止地运行catch块的System.out.println()表达式。

Scanner.nextLine()的目的是什么? 为什么这些场景中的每一个都有不同的表现?

import java.util.*; public class InputMismatchExceptionDemo { public static void main(String[] args) { Scanner input = new Scanner(System.in); boolean continueInput = true; do { try{ System.out.print("Enter an integer: "); int number = input.nextInt(); System.out.println( "The number entered is " + number); continueInput = false; } catch (InputMismatchException ex) { System.out.println("Try again. (" + "Incorrect input: an integer is required)"); input.nextLine(); } } while (continueInput); } } 

感谢大家

当任何nextXxx(...)方法失败时,扫描仪的输入光标将重置为调用之前的位置。 因此,exception处理程序中nextLine()调用的目的是跳过“垃圾”号…准备下次尝试让用户输入一个数字。

当你删除nextLine() ,代码反复尝试重新分析相同的“垃圾”号码。


值得注意的是,如果nextInt()调用成功,则扫描程序将紧跟在数字的最后一个字符之后。 假设您通过控制台输入/输出与用户交互, 可能有必要或建议通过调用nextLine()来使用剩余的行(直到换行符nextLine() 。 这取决于您的应用程序下一步要做什么。