To process real-valued input from the keyboard, we just need
to use a different method. As we would
suspect, the method is called nextDouble. Let’s use the method in a program that computes
the volume of a sphere given the radius (it’s just // this program will
compute the volume of a sphere given its radius import java.util.Scanner; public class SphereVolume { public static void main(String args[]) { // Create a Scanner object ‘input’ Scanner input = new Scanner(System.in); // prompt the user to enter the radius as
a real value System.out.print("Enter
the radius: "); // store the result in ‘radius' double radius = input.nextDouble(); // compute the volume and store in
'volume' (a double) double volume = (4.0 / 3.0) * 3.141592654
* radius; // display the result System.out.println("The volume of
a sphere with a radius of " + radius + " is " + volume); } } |