Write a Cart class with a private map of product→quantity, a maximum of 5 per product, and methods add, remove, total(prices) and an unmodifiable items() view.
Solution
Main.java
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
class Cart {
private static final int MAX_PER_ITEM = 5;
private final Map<String, Integer> items = new LinkedHashMap<>();
public String add(String product, int qty) {
int now = items.getOrDefault(product, 0);
if (qty <= 0) return "bad quantity";
if (now + qty > MAX_PER_ITEM) return product + ": max " + MAX_PER_ITEM;
items.put(product, now + qty);
return product + " x" + (now + qty);
}
public boolean remove(String product) { return items.remove(product) != null; }
public double total(Map<String, Double> prices) {
double t = 0;
for (var e : items.entrySet()) t += prices.getOrDefault(e.getKey(), 0.0) * e.getValue();
return t;
}
public Map<String, Integer> items() { return Collections.unmodifiableMap(items); }
}
public class Main {
public static void main(String[] args) {
Map<String, Double> prices = Map.of("pen", 20.0, "book", 150.0, "bag", 899.0);
Cart c = new Cart();
System.out.println(c.add("pen", 3) + ", " + c.add("pen", 3) + ", " + c.add("book", 2) + ", " + c.add("bag", 0) + ", " + c.add("bag", 1));
System.out.println(c.remove("book") + " " + c.remove("lamp") + " " + c.items() + " total " + c.total(prices));
}
}
Output Verified by compiling and running
pen x3, pen: max 5, book x2, bad quantity, bag x1
true false {pen=3, bag=1} total 959.0
Every change goes through add or remove, which enforce the rules; the view lets callers read the items without changing them.
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!
We use Google Analytics cookies to see how LearnFrenzy is used and make it better, and Google AdSense to keep it free.
No analytics or ad cookies are set until you accept. Privacy Policy
·
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!