In: Computer Science
Create a ShoppingCart class in java that simulates the operation of a shopping cart. The ShoppingCart instance should contain a BagInterface implementation that will serve to hold the Items that will be added to the cart. Use the implementation of the Item object provided in Item.java. Note that the price is stored as the number of cents so it can be represented as an int (e.g., an Item worth $19.99 would have price = 1999).
Your shopping cart should support the following operations:
Add an item
Add multiple quantities of a given item (e.g., add 3 of Item __)
Remove an unspecified item
Remove a specified item
Checkout – should "scan" each Item in the shopping cart (and display its
information), sum up the total cost and display the total cost
Check budget – Given a budget amount, check to see if the budget is large
enough to pay for everything in the cart. If not, remove an Item from the shopping cart, one at a time, until under budget.
Write a driver program to test out your ShoppingCart implementation.
Write a driver program to test out your ShoppingCart implementation.
Note that your implementation should be as generalized as possible. In other words, you should be able to create a ShoppingCart instance using any of the bag implementations and have all of the methods still work.
Also, think before you code. If you find yourself re-writing the substantive bag operations, you are doing it wrong.
And of course, your code should be documented with header comments for each method and in-line comments as needed.
GIVEN DATA
Program-
/** * Item.java - implementation of an Item to be placed in ShoppingCart */ public class Item { private String name; private int price; //in cents //Constructor public Item(String n, int p) { name = n; price = p; } public boolean equals(Item other) { return this.name.equals(other.name) && this.price == other.price; } //displays name of item and price in properly formatted manner public String toString() { return name + ", price: $" + price/100 + "." + price%100; } //Getter methods public int getPrice() { return price; } public String getName() { return name; } }
// An interface describing the opeations of a bag
// of objects
public interface BagInterface<T> { //Gets the current number of entries in the bag public int getCurrentSize();
// isEmpty() - Returns true if there's
// nothing in the bag // Returns false if not public boolean isEmpty();
// Adds the entry to the bag
// Return true if successful, false if not public boolean add(T newEntry);
// Removes one occurrence of an entry
// to the bag
// Returns it if successful, null if not public T remove();
// Removes one occurrence of an entry
// to the bag
// Returns true if successful, false if not public boolean remove(T anEntry);
// Removes everything from the bag public void clear();
// Returns the number of such items in the bag public int getFrequencyOf(T anEntry);
// Returns true if there is an item of this // type in the bag, false if not public boolean contains(T anEntry);
// Returns everything in the bag as an array public T[] toArray();
}
Item.java
// A class of items for sale.
public class Item
{ private String description; private int price;
public Item(String productDescription, int productPrice) {
description = productDescription; price = productPrice; } // end constructor
public String getDescription() { return description;
} // end getDescription
public int getPrice() {
return price; } // end getPrice
public String toString() { return description + "\t$" + price / 100
+ "." + price % 100;
} // end toString
} // end Item
OnlineShopper.java
// A class that maintains a shopping cart for // an online store.
public class OnlineShopper { public static void main(String[] args) {
Item[] items = { new Item("Bird feeder", 2050), new Item("Squirrel guard", 1547), new Item("Bird bath", 4499), new Item("Sunflower seeds", 1295)};
BagInterface<Item> shoppingCart = new ArrayBag<>();
int totalCost = 0;
// statements that add selected items
// to the shopping cart:
for (int index = 0; index < items.length; index++) {
// simulates getting item from shopper Item nextItem = items[index]; shoppingCart.add(nextItem); totalCost
= totalCost + nextItem.getPrice();
} // end for
while (!shoppingCart.isEmpty())
System.out.println(shoppingCart.remove());
System.out.println("Total cost: "
+ "\t$" + totalCost / 100 + "."
+ totalCost % 100);
} // end main
} // end OnlineShopper
// A class that represents a coin.
public class Coin
{ private enum CoinSide {HEADS, TAILS} private CoinName myName; private int value; // in cents private int year; // mint year private CoinSide sideUp;
// Constructs an object for the coin having
// a given value and mint year. The visible
// side of the new coin is set at random.
public Coin(int coinValue, int mintYear) { switch (coinValue) { case 1: myName = CoinName.PENNY; break; case 5: myName = CoinName.NICKEL; break; case 10: myName = CoinName.DIME; break; case 25: myName = CoinName.QUARTER; break;
case 50: myName = CoinName.FIFTY_CENT; break;
case 100: myName = CoinName.DOLLAR; break;
default: myName = CoinName.PENNY; break;
} // end switch
value = coinValue; year = mintYear; sideUp = getToss();
} // end constructor
// Constructs an object for the coin having a
// given name and mint year. The visible side // of the new coin is set at random.
public Coin(CoinName name, int mintYear) { switch (name) { case PENNY: value = 1; break; case NICKEL: value = 5; break; case DIME: value = 10; break; case QUARTER: value = 25; break; case FIFTY_CENT: value = 50; break; case DOLLAR: value = 100; break; default: value = 1; break;
} // end switch
myName = name; year = mintYear; sideUp = getToss();
} // end constructor
// Returns the name of the coin. public CoinName getCoinName() { return myName;
} // end getCoinName
// Returns the value of the coin in cents.
public int getValue() { return value;
} // end getValue
// Returns the coin's mint year as an integer. public int getYear() { return year;
} // end getYear
// Returns "HEADS" if the coin is // heads-side up; otherwise, returns "TAILS" public String getSideUp() { return sideUp.toString();
} // end getSideUp
// Returns true if the coin is heads-side up.
public boolean isHeads() {
return sideUp == CoinSide.HEADS;
} // end isHeads
// Returns true if the coin is tails-side up. public boolean isTails() { return sideUp == CoinSide.TAILS;
} // end isTails
// Tosses the coin; sideUp will be either // HEADS or TAILS at random.
public void toss() { sideUp = getToss();
} // end toss
// Returns the coin as a string in the form
// value/year/side-up" public String toString() { return value + "/" + year + "/" + sideUp;
} // end toString
// Returns a random value of either // HEADS or TAILS.
private CoinSide getToss() { CoinSide result; if (Math.random() < 0.5)
result = CoinSide.HEADS;
else
result = CoinSide.TAILS;
return result;
} // end getToss
} // end Coin
Piggy Bank.java
// A class that implements a piggy bank by // using a bag.
public class PiggyBank { private BagInterface<Coin> coins;
public PiggyBank() { coins = new ArrayBag<>(); } // end default constructor
public boolean add(Coin aCoin) { return coins.add(aCoin);
} // end add
public Coin remove() {
return coins.remove(); } // end remove
public boolean isEmpty() {
return coins.isEmpty();
} // end isEmpty
} // end PiggyBank
PiggyBankExample.java
// A class that demonstrates the class PiggyBank.
public class PiggyBankExample { public static void main(String[] args) { PiggyBank myBank = new PiggyBank();
addCoin(new Coin(1, 2010), myBank); addCoin(new Coin(5, 2011), myBank); addCoin(new Coin(10, 2000), myBank); addCoin(new Coin(25, 2012), myBank);
System.out.println
("Removing all the coins:"); int amountRemoved = 0;
while (!myBank.isEmpty()) {
Coin removedCoin = myBank.remove();
System.out.println("Removed a "
+ removedCoin.getCoinName() + "."); amountRemoved
= amountRemoved + removedCoin.getValue();
} // end while
System.out.println("All done. Removed “
+ amountRemoved + " cents.");
} // end main
private static void addCoin(Coin aCoin,
PiggyBank aBank) {
if (aBank.add(aCoin))
System.out.println("Added a " + aCoin.getCoinName() + ".");
else
System.out.println("Tried to add a "
+ aCoin.getCoinName()
+ ", but couldn't");
} // end addCoin
} // end PiggyBankExample
Set.java
// An interface that specified a set of objects public interface SetInterface <T> { public int getCurrentSize(); public boolean isEmpty();
// add() - adds an member to the set
// avoiding duplicates
// Returns true if successful // Returns false if not public boolean add(T newEntry);
// remove() - Removes anEntry from the set.
// Returns true if sucessful // Returs if not. public boolean remove(T anEntry);
public T remove(); public void clear();
public boolean contains(T anEntry); public T[] toArray();
}
BagArray.java
// A class of bags whose entries are stored in a // fixed-size array.
public final class ArrayBag<T> implements BagInterface<T> {
private final T[] bag; private int numberOfEntries; private boolean initialized = false; private static final int DEFAULT_CAPACITY = 25;
private static final int MAX_CAPACITY = 10000;
// ArrayBag() - Creates an empty bag whose // initial capacity is 25.
public ArrayBag() {
this(DEFAULT_CAPACITY);
}
// ArrayBag() - Creates an empty bag having a // given capacity.
public ArrayBag(int desiredCapacity) { if (desiredCapacity <= MAX_CAPACITY) {
// The cast is safe because the new array
// contains null entries
@SuppressWarnings("unchecked")
// Unchecked cast
T[] tempBag = (T[]) new Object[desiredCapacity];
bag = tempBag; numberOfEntries = 0; initialized = true;
}
else
throw new IllegalStateException
("Attempt to create a bag "
+ "whose capacity exceeds "
+ "allowed maximum.");
}
Making the Implementation
Secure
// checkInitialization() - throws an exception // if this object is not initialized.
private void checkInitialization() { if (!initialized) throw new SecurityException
("ArrayBag object is not initialized "
+ "properly.");
}
// add() - Adds a new entry to this bag public boolean add(T newEntry) { checkInitialization(); boolean result = true;
if (isArrayFull()) { result = false;
} else {
// Assertion: result is true here bag[numberOfEntries] = newEntry; numberOfEntries++;
} return result;
}
// isArrayFull() - Returns true if the array
// bag is full, or false if // not.
private boolean isArrayFull() {
return numberOfEntries >= bag.length;
}
// toArray() - retrieves all entries that are // in this bag in an array.
public T[] toArray() { checkInitialization();
// The cast is safe because the new array // contains null entries.
@SuppressWarnings("unchecked")
// Unchecked cast
T[] result = (T[]) new Object[numberOfEntries];
for (int index = 0; index < numberOfEntries; index++) {
result[index] = bag[index];
}
return result;
}
Methods That Remove Items
// clear() - Removes all entries from this bag.
public void clear() {
while (!isEmpty())
remove();
}
Methods That Remove Items
// remove() - removes one unspecified entry // from this bag, if possible.
// Returns the removed entry, if the
// removal was successful, or null. public T remove() {
checkInitialization();
T result = removeEntry(numberOfEntries - 1);
return result;
} // end remove
Methods That Remove Items
// remove() - removes one occurrence of a given // entry from this bag.
// Returns True if the removal was // successful, or false if not. public boolean remove(T anEntry) { checkInitialization(); int index = getIndexOf(anEntry); T result = removeEntry(index);
return anEntry.equals(result);
}
// at a given index within the // array.
// If no such entry exists, // returns null.
// Precondition:
// 0 <= givenIndex < numberOfEntries.
// Precondition:
// checkInitialization has been called. private T removeEntry(int givenIndex) {
T result = null;
if (!isEmpty() && (givenIndex >= 0)) {
// Entry to remove result = bag[givenIndex]; int lastIndex = numberOfEntries - 1;
// Replace entry to remove with last entry bag[givenIndex] = bag[lastIndex];
// Remove reference to last entry bag[lastIndex] = null; numberOfEntries--;
}
return result;
}
// getIndexOf() - returns the index of the
// entry, if located, // or -1 otherwise. // Precondition: checkInitialization has been // called.
private int getIndexOf(T anEntry) {
int where = -1; boolean found = false; int index = 0;
while (!found && (index < numberOfEntries)) { if (anEntry.equals(bag[index])) { found = true; where = index;
} index++;
} // end while
// Assertion: If where > -1, anEntry is in
// the array bag, and it equals
// bag[where]; otherwise, anEntry // is not in the array.
return where;
}
// isEmpty() - sees whether this bag is empty.
// Returns true if this bag is // empty, or false if not.
public boolean isEmpty() {
return numberOfEntries == 0;
}
// getCurrentSize() - gets the current number // of entries in this bag.
public int getCurrentSize() {
return numberOfEntries;
}
// getFrequency() - Counts the number of times
// given entry appears in this // bag.
// Returns the number of times
// anEntry appears in this // bag.
public int getFrequencyOf(T anEntry) { checkInitialization(); int counter = 0;
for (int index = 0; index < numberOfEntries; index++) {
if (anEntry.equals(bag[index])) {
counter++;
} // end if
} // end for
return counter;
}
// contains() - Determines if this bag contains // a given entry.
// Returns true if this bag
// contains anEntry, or false // otherwise.
public boolean contains(T anEntry) { checkInitialization(); return getIndexOf(anEntry) > -1; // or >= 0
}
// checkInitialization() - throws an exception // if this object is not initialized. private void checkInitialization() {
if (!initialized)
throw new SecurityException
("ArrayBag object is not initialized "
+ "properly.");
}
i hope it helps..
If you have any doubts please comment and please don't dislike.
PLEASE GIVE ME A LIKE. ITS VERY IMPORTANT FOR ME