-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathShoppingCart.java
35 lines (29 loc) · 947 Bytes
/
ShoppingCart.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import java.util.HashMap;
import java.util.Map;
public class ShoppingCart {
private final Map<String, Integer> cart = new HashMap<>();
private final Map<String, Double> itemsAndPrices;
public ShoppingCart(Map<String, Double> itemsAndPrices) {
this.itemsAndPrices = itemsAndPrices;
}
public void addItem(String item, int quantity) {
if (itemsAndPrices.containsKey(item)) {
cart.put(item, quantity);
}
}
public void removeItem(String item) {
cart.remove(item);
}
public void updateQuantity(String item, int quantity) {
if (cart.containsKey(item)) {
cart.put(item, quantity);
}
}
public double calculateTotalPrice() {
double total = 0.0;
for (Map.Entry<String, Integer> entry : cart.entrySet()) {
total += entry.getValue() * itemsAndPrices.get(entry.getKey());
}
return total;
}
}