GroceryStore.java source, see below for HTML.
StoreManager.java source, below for HTML.
public interface GroceryItem
{
String getName(); // returns name of item
double getPrice(); // returns price of item
int getSize(); // returns #ounces (or size) of item
String getCategory(); // returns category of item
}
import java.util.ArrayList;
import java.util.Iterator;
public class GroceryStore
{
ArrayList myItems;
/**
* Creates an initially empty grocery store
*/
public GroceryStore()
{
myItems = new ArrayList();
}
/**
* Changes the price of the item associated with itemName
*/
public void setPrice(String itemName, double price)
{
GroceryItem item = getItem(itemName);
if (item != null) {
( (GItem) item).price = price;
}
}
/**
* returns the item associated with itemName
*/
public GroceryItem getItem(String itemName)
{
return getGItem(itemName);
}
/**
* returns a (possibly empty) ArrayList of all
* the items in the specified category
*/
public ArrayList getAllItems(String category)
{
ArrayList list = new ArrayList();
for(int k=0; k < myItems.size(); k++) {
GItem item = (GItem) myItems.get(k);
if (item.getCategory().equals(category)) {
list.add(item);
}
}
return list;
}
/**
* precondition: names.length == prices.length
* changes the price of the item associated with names[k]
* to the price specified by prices[k]
*/
public void changePrices(String[] names, double[] prices)
{
for(int k=0; k < names.length; k++) {
setPrice(names[k],prices[k]);
}
}
private GItem getGItem(String itemName)
{
Iterator it = myItems.iterator();
while (it.hasNext()) {
GItem gitem = (GItem) it.next();
if (gitem.getName().equals(itemName)) {
return gitem;
}
}
return null;
}
private class GItem implements GroceryItem
{
String name;
double price;
String category;
int size;
public String getName() { return name; }
public double getPrice() { return price; }
public int getSize() { return size; }
public String getCategory() { return category; }
}
}
import java.util.ArrayList;
public class StoreManager
{
/**
* returns the name of an item whose unit price is the lowest
* in the specified category; if no items in the specified
* category, returns "none"
*/
public String minUnitPrice(GroceryStore store, String category)
{
ArrayList list = store.getAllItems(category);
if (list.size() == 0) {
return "none";
}
GroceryItem minItem = (GroceryItem) list.get(0);
for(int k=1; k < list.size(); k++) {
GroceryItem current = (GroceryItem) list.get(k);
if (current.getPrice()/current.getSize() <
minItem.getPrice()/minItem.getSize()) {
minItem = current;
}
}
return minItem.getName();
}
}
Owen L. Astrachan
Last modified: Tue May 13 12:52:44 EDT 2003