Understanding the Scanner class
Scanner
(from the java.util
package) is a text scanner that can parse primitives and strings using regular expressions. A regular expression is a pattern that enables string manipulation. As it states so eloquently in the Java API: “A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.”
These nextXXX()
methods convert the tokens on the input stream into primitives. For example, if the user has typed in 23
, then nextInt()
would return an int
value of 23
; if the user typed in 45.89
, then nextDouble()
would return a double
value of 45.89
.
However, if the token on the input stream is not an integer and nextInt()
is called, an InputMismatchException
error is thrown. This could occur if the user types in "abc"
and nextInt()
is called. To protect against this, each of the nextXXX...