I have the following assignment:
Implement a basic shopping basket without using any predefined
collection libraries. Please comment your code to support your design
decision and any assumption that you make. Your shopping basket must
support the following two methods:-
void add(Item i, int n) - adds n copies of i to the basketint totalPrice()– compute the total price of the basket. The
total price must be returned in constant time; however,void add(Itemdoes not need to be returned in constant time.
i, int n)
I have implemented the shopping class like this but don’t getting the clue how to implement totalPrice method.
public class Shopping {
public void add(Item i, int n){
int totalCost = (int) (i.getItemPrice()*n);
}
public static void main(String arg[]){
Item item = new Item();
item.setItemPrice(10);
Shopping shopping = new Shopping();
shopping.add(item,4);
}
}
I have been asked this in a test. Does anyone can give me some idea how this can be done?
You can declare a member variable in the class, that you can used to store the total price in the basket. And every time you add items to the basket you can update the value of this variable.
Let’s say we add a member variable:
Then modify your add(…) method to add the value of totalCost to total and the only thing you should do in your totalPrice() method is return the value of total. You can initialize the variable total in the constructor.