-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathCart.java
77 lines (60 loc) · 1.84 KB
/
Cart.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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package Restaurants;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map.Entry;
public class Cart {
private HashMap<Item, Integer> items = new HashMap<Item, Integer>();
private Restaurant restaurant;
public Cart(Restaurant _restaurant) {
restaurant = _restaurant;
}
public Restaurant getRestaurant() {
return restaurant;
}
public HashMap<Item, Integer> getItems() {
return items;
}
public void addItem(Item item) {
// Add an item to order or increase quantity if it already exists
int quantity = 1;
if (items.containsKey(item)) {
quantity = items.get(item) + 1;
}
items.put(item, quantity);
}
public void removeItem(Item item) {
items.remove(item);
}
public double getTotalPrice() {
// Adds the price of all the items in the cart
double totalPrice = 0;
for (Entry<Item, Integer> entry : items.entrySet()) {
Item item = (Item) entry.getKey();
int quantity = (int) entry.getValue();
totalPrice += quantity * item.getPrice();
}
totalPrice = Math.round(totalPrice * 100.0) / 100.0;
return totalPrice;
}
public ArrayList<Item> displayItems() {
// Prints all items in cart in the following format
// X. [NAME] (QUANTITY)
ArrayList<Item> orderedItems = new ArrayList<>();
for (Entry<Item, Integer> entry : items.entrySet()) {
Item item = (Item) entry.getKey();
int quantity = (int) entry.getValue();
int idx = orderedItems.size();
orderedItems.add(item);
System.out.println(idx + ". " + item.getName() + " (" + quantity + ")");
}
System.out.println();
return orderedItems;
}
public void editItem(Item item, int newQuantity) {
// Edits the item quantity or removes if 0
if (newQuantity > 0)
items.put(item, newQuantity);
else
removeItem(item);
}
}