How to Read Decimal Numbers from the Keyboard in Java

By Barry Burd

When will you need to read decimal numbers from the keyboard in Java programming? SnitSoft is having a sale! For one week only, you can get the SnitSoft CD-ROM for the low price of just $5.75! Better hurry up and order one.

No, wait! The code has the price fixed at $5.95. You have to revise the program.

Input the amount from the keyboard.

image0.jpg

import java.util.Scanner;
class VersatileSnitSoft {
 public static void main(String args[]) {
  Scanner keyboard = new Scanner(System.in);
  double amount;
  System.out.print("What's the price of a CD-ROM? ");
  amount = keyboard.nextDouble();
  amount = amount + 25.00;
  System.out.print("We will bill $");
  System.out.print(amount);
  System.out.println(" to your credit card.");
  keyboard.close();
 }
}

Grouping separators vary from one country to another. This run is for a computer configured in the United States where 5.75 means “five and seventy-five hundredths.” But the run might look different on a computer that’s configured in a “comma country” — a country where 5,75 means “five and seventy-five hundredths.”

If you live in a comma country, and you type 5.75 exactly as it’s shown, you probably get an error message (an InputMismatchException). If so, change the number amounts in your file to match your country’s number format. When you do, you should be okay.

Though these be methods, yet there is madness in ‘t

Notice the call to the nextDouble. In Java, each type of input requires its own special method. If you’re getting a line of text, then nextLine works just fine. But if you’re reading stuff from the keyboard and you want that stuff to be interpreted as a number, you need a method like nextDouble.

You need to add an import declaration and some stuff about new Scanner(System.in).

Methods and assignments

Note how the keyboard.nextDouble is used. The call to method keyboard.nextDouble is part of an assignment statement. The computer can substitute something in place of a method call. The computer does this in the code. When you type 5.75 on the keyboard, the computer turns

amount = keyboard.nextDouble();

into

amount = 5.75;

(The computer doesn’t really rewrite the code in Listing 6-2. This amount = 5.75 line just illustrates the effect of the computer’s action.) In the second assignment statement, the computer adds 25.00 to the 5.75 that’s stored in amount.

Some method calls have this substitution effect, and others (like System.out.println) don’t.