/** This ShoppingList class represents an array of Items */ import java.io.*; import java.util.*; import java.text.*; public class ShoppingList { private Item [] list; /** For our (default) constructor, we ask the user to enter the number of * items, and the particulars for each of the items here. */ public ShoppingList() throws IOException { BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in)); System.out.print("how many items are you buying? "); int n = Integer.parseInt(kbd.readLine()); // allocate space for the shopping list list = new Item[n]; // for each item we want to buy, create an Item object // and put it in the array for (int i = 0; i < n; ++i) { System.out.print("enter name and price of item # " + (i+1) + ": "); String input = kbd.readLine(); StringTokenizer tok = new StringTokenizer(input, ", "); String itemName = tok.nextToken(); double itemPrice = Double.parseDouble(tok.nextToken()); Item thing = new Item(itemName, itemPrice); list[i] = thing; } } /** getTotal() adds up the price of each item on my shopping list. * Notice the way we find the price of each item -- the Item class has * an instance method called getPrice, because technically the price is * an attribute of the item and therefore "private" information. We can * see the price thanks to getPrice(), but can't change it. * Also note that list.length is the number of items in the array. */ public double getTotal() { double sum = 0.0; for (int i = 0; i < list.length; ++i) sum += list[i].getPrice(); return sum; } /** sortList() will sort the items in our list in descending order of * price. This is not the most efficient way of sorting, but it is * one of the more straightforward and easy to remember. The basic * idea is that we want to swap any elements on the list that appear out * of order. */ public void sortList() { for (int i = 0; i < list.length; ++i) for (int j = i+1; j < list.length; ++j) if (list[i].getPrice() < list[j].getPrice()) { Item tempItem = new Item(list[i].getName(), list[i].getPrice()); list[i] = list[j]; list[j] = tempItem; } } /** printList() will print the shopping list in an attractive format. * We could have written this function as toString(), so that we create * and build the string representing the entire shopping list, rather than * printing the whole thing out here. */ public void printList() { for (int i = 0; i < list.length; ++i) { System.out.println(list[i]); } // at the end, print a total NumberFormat f = NumberFormat.getNumberInstance(); f.setMaximumIntegerDigits(4); f.setMinimumIntegerDigits(1); f.setMaximumFractionDigits(2); f.setMinimumFractionDigits(2); String expr = f.format(getTotal()); while (expr.length() < 8) expr = " " + expr; System.out.println("----------------------------------------"); System.out.println(" $ " + expr + " TOTAL"); } }