What do you suppose happens if the user types in
an integer value, like 211
?
The characters are converted into a double
.
If the input characters can be converted into a
double
, then that is done, even if
the input characters lack a decimal point.
If the input starts with characters that can NOT be converted into a double, then Java throws and exception and this program halts. (A later chapter will discuss how to deal with exceptions.) For example:
C:\temp>java DoubleDouble Enter a double: rats Exception in thread "main" java.util.InputMismatchException at java.util.Scanner.throwFor(Unknown Source) at java.util.Scanner.next(Unknown Source) at java.util.Scanner.nextDouble(Unknown Source) at DoubleDouble.main(DoubleDouble.java:14)
If the input starts with characters that can be converted into a double, and is followed by one or more spaces, then those characters are converted regardless of what follows. For example:
C:\temp>java DoubleDouble Enter a double: 3.14 and more characters value: 3.14 twice value: 6.28
A subsequent call to a method that expects digits (such as nextDouble()
)
will try to convert the "and" and will throw an exception.
Will the following input work with the above program?
C:\temp>java DoubleDouble Enter a double: -97.65 ?????