go to previous page   go to home page   hear noise   go to next page


No. Integer and floating point types use different bit patterns to represent values.

Reading a double from the Keyboard

The 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.

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 converts a string of input characters into primitive type double, and then prints out that value and twice that 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 );

The program writes:

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?