| CIT 591 Example of Objects: GroceryStore Fall 2002, David Matuszek |
Here is the complete code for the GroceryStore application. It's
also available as a BlueJ project in this zip
file.
GroceryStore.java |
public class GroceryStore {
// instance variables
Clerk myClerk;
public int KINDS_OF_ITEMS = 4;
public GroceryItem[ ] item = new GroceryItem[KINDS_OF_ITEMS];
public int[ ] itemCount = new int[KINDS_OF_ITEMS];
double money = 1000.00;
// constructor
GroceryStore() {
item[0] = new GroceryItem("milk", 2.12);
item[1] = new GroceryItem("butter", 2.50);
item[2] = new GroceryItem("eggs", 0.89);
item[3] = new GroceryItem("bread", 1.59);
for (int i = 0; i < KINDS_OF_ITEMS; i++) {
itemCount[i] = 50; // the store has lots of everything
}
}
public static void main(String args[]) {
GroceryStore store = new GroceryStore();
Clerk clerk = new Clerk();
store.hire(clerk);
Customer customer = new Customer();
customer.shop(store);
}
public void hire(Clerk clerk) {
myClerk = clerk;
clerk.takePosition(this); // "this" = this store
}
public Clerk getClerk() {
return myClerk;
}
}
|
Customer.java |
import java.util.*; // for Random
public class Customer {
GroceryItem[ ] myShoppingBasket = new GroceryItem[20];
Random random = new Random();
double myMoney = 100.00;
public void shop(GroceryStore store) {
selectGroceries(store); // because the store holds the groceries
checkOut(store);
}
public void selectGroceries(GroceryStore store) {
int itemsInMyBasket = 0;
for (int i = 0; i < store.KINDS_OF_ITEMS; i++) { // for each kind of item
for (int j = 0; j < 3; j++) { // choose up to 3 of it
if (random.nextInt(2) == 1) {
myShoppingBasket[itemsInMyBasket] = store.item[i];
store.itemCount[i] = store.itemCount[i] - 1;
itemsInMyBasket = itemsInMyBasket + 1;
}
}
}
}
void checkOut(GroceryStore store) {
Clerk clerk = store.getClerk();
double total = clerk.ringUp(myShoppingBasket);
myMoney = myMoney - total;
clerk.pay(total);
}
}
|
Clerk.java |
public class Clerk {
GroceryStore myStore;
public void takePosition(GroceryStore store) {
myStore = store;
}
public double ringUp(GroceryItem[] item) {
double total = 0;
int itemNumber = 0;
while (item[itemNumber] != null) {
total = total + item[itemNumber].price;
System.out.println(item[itemNumber].name + " " +
item[itemNumber].price);
itemNumber = itemNumber + 1;
}
System.out.println("TOTAL " + total);
return total;
}
public void pay(double amount) {
myStore.money = myStore.money + amount;
}
}
|
GroceryItem.java |
public class GroceryItem {
// Instance variables
public String name;
public double price;
// Constructor
GroceryItem(String name, double price) {
this.name = name;
this.price = price;
}
}
|
Example output |
milk 2.12 butter 2.5 butter 2.5 eggs 0.89 eggs 0.89 TOTAL 8.9 |