Untitled
unknown
plain_text
13 days ago
1.2 kB
3
Indexable
Never
import java.util.HashMap; import java.util.Map; public class ShoppingCart { private Map<Product, Integer> cartItems = new HashMap<>(); public void addProduct(Product product, int quantity) { cartItems.put(product, cartItems.getOrDefault(product, 0) + quantity); } public void viewCart() { double total = 0; if (cartItems.isEmpty()) { System.out.println("Your cart is empty."); return; } for (Map.Entry<Product, Integer> entry : cartItems.entrySet()) { Product product = entry.getKey(); int quantity = entry.getValue(); double price = product.getPrice() * quantity; total += price; System.out.println(product + ", Quantity: " + quantity + ", Subtotal: $" + price); } System.out.println("Total Amount: $" + total); } public void checkout() { if (cartItems.isEmpty()) { System.out.println("Your cart is empty."); } else { viewCart(); System.out.println("Thank you for your purchase!"); cartItems.clear(); } } }
Leave a Comment