13.7: Validating Input
- Page ID
- 18821
\( \newcommand{\vecs}[1]{\overset { \scriptstyle \rightharpoonup} {\mathbf{#1}} } \) \( \newcommand{\vecd}[1]{\overset{-\!-\!\rightharpoonup}{\vphantom{a}\smash {#1}}} \)\(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\) \(\newcommand{\id}{\mathrm{id}}\) \( \newcommand{\Span}{\mathrm{span}}\) \( \newcommand{\kernel}{\mathrm{null}\,}\) \( \newcommand{\range}{\mathrm{range}\,}\) \( \newcommand{\RealPart}{\mathrm{Re}}\) \( \newcommand{\ImaginaryPart}{\mathrm{Im}}\) \( \newcommand{\Argument}{\mathrm{Arg}}\) \( \newcommand{\norm}[1]{\| #1 \|}\) \( \newcommand{\inner}[2]{\langle #1, #2 \rangle}\) \( \newcommand{\Span}{\mathrm{span}}\)\(\newcommand{\AA}{\unicode[.8,0]{x212B}}\)
Here is a method that uses printLogarithm
from the previous section:
public static void scanDouble(Scanner in) { System.out.print("Enter a number: "); double x = in.nextDouble(); printLogarithm(x); }
This example uses nextDouble
, so the Scanner
(provided by the main
method) tries to read a double
. If the user enters a floating-point number, the Scanner
converts it to a double
. But if the user types anything else, the Scanner
throws an InputMismatchException
.
We can prevent this error by checking the input before parsing it:
public static void scanDouble(Scanner in) { System.out.print("Enter a number: "); if (!in.hasNextDouble()) { String word = in.next(); System.err.println(word + " is not a number"); return; } double x = in.nextDouble(); printLogarithm(x); }
The Scanner
class provides hasNextDouble
, which checks whether the next token in the input stream can be interpreted as a double
. If so, we can call nextDouble
with no chance of throwing an exception. If not, we display an error message and return.