6.5 Type-Safe Input Using Scanner

One problem with reading input using Scanner is that if the next token does not match the data type we expect, an InputMismatchException is generated, which stops execution of the program. This could be caused by a simple typo on the user’s part; for example, the user may type a letter or other nonnumeric character when our program prompts for an integer. To illustrate this problem, Example 6.7 shows a small program that prompts the user for an integer and calls the nextInt method of the Scanner class to read the integer, and Figure 6.10 shows the InputMismatchException generated when the user enters an a instead of an integer. Notice that the program ends when the exception is generated; we never execute ...

Get Java Illuminated, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.