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 they use are completely different.
Here is the 64-bit pattern that represents 221 using data type long
(the spaces are not part of the pattern):
0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 1101 1101
Here is the 64-bit pattern that represents 221.0 using data type double
:
0100 0000 0110 1011 1010 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000 0000
And here is the 64-bit pattern for the four characters " 221
"
0000 0000 0010 0000 0000 0011 0010 0000 0000 0011 0010 0000 0000 0011 0000 0001
Scanner
does floating point input
in a way similar to integer input.
Use a Scanner
object to scan through a stream of
input characters and to convert them into a float
or a double
.
The methods that do this are nextFloat()
and nextDouble()
.
Here is a program that inputs a string of characters and
converts that string
into primitive type double
.
The value is multiplied the by two,
and then the original value and its double are
converted back into characters and written to the screen.
import java.io.*;
import java.util.Scanner;
public 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 );
}
}
The program writes:
C:\temp>java DoubleDouble Enter a double: 3.14 value: 3.14 twice value: 6.28
Here is another run of the program:
C:\temp>java DoubleDouble Enter a double: 0003.140000 value: 3.14 twice value: 6.28
The characters 0003.140000
are converted into the same 64 bit pattern as the characters 3.14
.
On output, it is that 64 bit double that results in the characters that are printed, not the original characters.
What do you suppose scan.nextDouble()
returns if the user types in
an integer value, like 211
?