No. Integer and floating point types use different bit patterns to represent values.
double
from the KeyboardThe scheme used to represent integers is completely different from the scheme used to represent floating point. Even though you might regard 221 and 221.0 as equivalent, the bit patterns that represent each one are completely different.
Floating point input using
java.io
is similar to integer input.
A Scanner
object is used to scan through a stream of
input characters and convert them into a float
or a double
.
The methods that do this are nextFloat()
and nextDouble()
.
Here is a program that converts a String of characters
into primitive type double
,
and then prints out the value and twice the value:
// This program requires Java 1.5 or higher // import java.io.*; import java.util.Scanner; class DoubleDouble { public static void main (String[] args) { double value; Scanner scan = new Scanner( System.in ); System.out.print("Enter a double:"); value = scan.nextDouble(); System.out.println("value: " + value +" twice value: " + 2.0*value ); } }
Running the program writes the following to the screen:
C:\temp>java DoubleDouble Enter a double: 3.14 value: 3.14 twice value: 6.28
It would be worth your effort to copy this program to a file and to compile and run it.
What do you suppose happens if the user types in
an integer value, like 211
?