Question 2
Back to Exercise
Model Product (name, price) and Cart (a list of products with quantities) classes; add items, change a quantity, remove one, and print the bill.
Solution
import java.util.LinkedHashMap;
import java.util.Map;
class Product {
final String name;
final double price;
Product(String name, double price) { this.name = name; this.price = price; }
}
class Cart {
private final Map<Product, Integer> items = new LinkedHashMap<>();
void add(Product p, int qty) { items.merge(p, qty, Integer::sum); }
void remove(Product p) { items.remove(p); }
double total() {
double t = 0;
for (Map.Entry<Product, Integer> e : items.entrySet()) t += e.getKey().price * e.getValue();
return t;
}
void print() {
items.forEach((p, q) -> System.out.printf("%-10s %2d x %7.2f = %8.2f%n", p.name, q, p.price, p.price * q));
System.out.printf("%-10s %22.2f%n", "TOTAL", total());
}
}
public class Main {
public static void main(String[] args) {
Product pen = new Product("Pen", 20), book = new Product("Notebook", 60), bag = new Product("Backpack", 899);
Cart cart = new Cart();
cart.add(pen, 3);
cart.add(book, 2);
cart.add(bag, 1);
cart.add(pen, 2); // same product object: quantity adds up
cart.remove(book);
cart.print();
}
}
Pen 5 x 20.00 = 100.00 Backpack 1 x 899.00 = 899.00 TOTAL 999.00
Product does not override equals/hashCode, so the map uses object identity – adding the same pen object again merges its quantity.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!