Program works fine, just need to know how to format the output of the Array of Objects (the prices), as currency (i.e. $33.33). Here is the code. Thanks.
NOTE: I tried the NumberFormat, as you can see, but xould not get it to work...kept getting an exception.
CODE:
Menu Class
Item ClassCode:import java.util.Scanner; import java.util.Arrays; import java.text.*; // Create Menu Class public class Menu { // Create main Method public static void main(String[] args) { // Create Array, declare variables, create Scanner Item[] menu_items = new Item[30]; Scanner sc = new Scanner(System.in); NumberFormat currency = new DecimalFormat("#,###.00"); // Prompt the user for item names and prices, and put these values into the array of objects. System.out.println("Please enter item names on one line followed by a price on the next line"); System.out.println("Enter STOP when finished."); int count; double price; String name; for (count = 0; count < menu_items.length; ++count) { name = sc.nextLine(); if (name.equalsIgnoreCase("STOP")) break; price = Double.parseDouble(sc.nextLine()); menu_items[count] = new Item(name, price); } // Print out the menu System.out.println("Wings Coffee Shop Menu"); System.out.println("Menu Item Price"); for (int i = 0 ;i < count; ++i) System.out.println(menu_items[i].toString()); } }
Code:// Create Item Class public class Item { private String item_name; private double item_price; // MenuItems Constructor that takes a String and Double public Item(String name, double price) { setName(name);setPrice(price); } // Setters public void setName(String name) {item_name = name;} public void setPrice(double price) {item_price = price;} // Getters public String name() {return item_name;} public double price() {return item_price;} // toString() Method public String toString() { // Format output - pad name StringBuffer result = new StringBuffer(name()); for (int i = 20 - name().length(); i > 0; --i) result.append(' '); result.append(price()); return result.toString(); } }


Reply With Quote