What do you suppose happens in this program if the user types in
an integer value, like 211?
scan.nextDouble() converts the characters into a double.
You don't have to supply a decimal point.
scan.nextDouble() converts 211 or
211.0 or 211.00 or 0211.0 into the same 64-bit double.
But the other direction does not work:
scan.nextInt() will throw an Exception if it encounters a decimal point.
The input characters are converted into a
double, if that is possible, even if
the input characters lack a decimal point.
If the input characters can NOT be converted into a
double,
then Java throws an exception and the 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)
The input might start with characters that can be converted,
followed by one or more spaces and perhaps additional characters.
If that happens,
nextDouble() scans in only the characters that can be converted.
C:\temp>java DoubleDouble Enter a double: 3.14 and more characters value: 3.14 twice value: 6.28
If the program had another call to nextDouble()
it would start where the previous call stopped and
would find characters that can't be converted,
and would throw an exception.
Will the following input work with the above program?
C:\temp>java DoubleDouble Enter a double: -97.65