What do you suppose happens if the user types in
an integer value, like
The characters are converted into a
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 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)
If the input starts with characters that can be converted into a double 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
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 ?????