A shop keeps its orders in a cart. Build two classes that work together: a LineItem is one row of the cart (a product, its price and how many were bought), and a Cart holds many rows and adds them up. The cart has line items (composition), it is not one.
LineItem
- Public fields
String name,double price,int quantity. LineItem(String name, double price, int quantity)stores the three values withthis..double subtotal()returnsprice * quantity.
Cart
- It keeps its items in
private List<LineItem> items = new ArrayList<>(). void add(LineItem item)appends the item to the list.double total()returns the sum of the subtotals of all items: startdouble sum = 0, loop over the items, returnsum.
Rules:
- The total is worked out every time it is asked for, from the items in the cart at that moment. Adding an item later changes the next total.
- An empty cart has a total of
0. - An item with price 5 and quantity 3 has a subtotal of 15.
- Prices in the driver are whole numbers.
Prices are double, so the driver casts the result with (int) to print 75 and not 75.0. The driver lives in Solution.mainFunction().
The driver (already in the starter code, don't change it) creates an empty cart, checks one subtotal, then fills a cart and prints the total twice:
class Solution {
public void mainFunction() {
Cart empty = new Cart();
System.out.println("Empty: " + (int)empty.total());
LineItem apple = new LineItem("Apple", 5, 3);
System.out.println("Subtotal: " + (int)apple.subtotal());
Cart cart = new Cart();
cart.add(apple);
cart.add(new LineItem("Bread", 20, 3));
System.out.println("Total: " + (int)cart.total());
cart.add(new LineItem("Milk", 10, 2));
System.out.println("Total: " + (int)cart.total());
}
}
Expected output:
Empty: 0 Subtotal: 15 Total: 75 Total: 95
Write
LineItem (fields, constructor, subtotal) first, then Cart with its List.
for (LineItem item : items) sum += item.subtotal();
class LineItem {
public String name;
public double price;
public int quantity;
public LineItem(String name, double price, int quantity) {
this.name = name;
this.price = price;
this.quantity = quantity;
}
public double subtotal() {
return price * quantity;
}
}
class Cart {
private List<LineItem> items = new ArrayList<>();
public void add(LineItem item) {
items.add(item);
}
public double total() {
double sum = 0;
for (LineItem item : items) sum += item.subtotal();
return sum;
}
}
class Solution {
public void mainFunction() {
Cart empty = new Cart();
System.out.println("Empty: " + (int)empty.total());
LineItem apple = new LineItem("Apple", 5, 3);
System.out.println("Subtotal: " + (int)apple.subtotal());
Cart cart = new Cart();
cart.add(apple);
cart.add(new LineItem("Bread", 20, 3));
System.out.println("Total: " + (int)cart.total());
cart.add(new LineItem("Milk", 10, 2));
System.out.println("Total: " + (int)cart.total());
}
}
Free plan: 30 tutor messages. Premium is unlimited.
