An example in Java for dummies:
"The Java API has a class named NumberFormat, and the NumberFormat class has a static method named getCurrencyInstance. When you call NumberFormat.getCurrencyInstance() with nothing inside the parentheses, you get an object that can mold numbers into U.S. currency amounts. Listing 18-7 has an example."
"The currency object has a format method. So to get the appropriate bunch of characters into the niceTotal variable, you call the currency object’s format method. You apply this format method to the variable total."
I'm wondering why this class instantiation involves a method.
Why is it NumberFormat currency =
NumberFormat.getCurrencyInstance();
instead of NumberFormat currency = new Numberformat(); ?
import java.text.NumberFormat; import java.util.Scanner; class BetterProcessData { public static void main(String args[]) { Scanner myScanner = new Scanner(System.in); double amount; boolean taxable; double total; NumberFormat currency = NumberFormat.getCurrencyInstance(); String niceTotal; System.out.print("Amount: "); amount = myScanner.nextDouble(); System.out.print("Taxable? (true/false) "); taxable = myScanner.nextBoolean(); if (taxable) { total = amount * 1.05; } else { total = amount; } niceTotal = currency.format(total); System.out.print("Total: "); System.out.println(niceTotal); } }