-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCartManager.java
More file actions
69 lines (55 loc) · 2.25 KB
/
CartManager.java
File metadata and controls
69 lines (55 loc) · 2.25 KB
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
package oopslogic.grocerysystem;
import java.io.File;
import java.io.PrintWriter;
import java.util.*;
public class CartManager {
private final Map<GroceryItem, Integer> cart = new LinkedHashMap<>();
public void addToCart(GroceryItem item, int quantity) {
cart.put(item, cart.getOrDefault(item, 0) + quantity);
}
public void printReceipt() {
double total = 0;
StringBuilder receipt = new StringBuilder("\n===== FINAL RECEIPT =====\n");
for (Map.Entry<GroceryItem, Integer> entry : cart.entrySet()) {
GroceryItem item = entry.getKey();
int qty = entry.getValue();
double cost = item.getPrice() * qty;
total += cost;
receipt.append(String.format("%s x%d = ₹%.2f\n", item.getName(), qty, cost));
}
receipt.append("---------------------------\n");
receipt.append(String.format("Total Bill: ₹%.2f\n", total));
receipt.append("===========================\n");
System.out.println(receipt);
saveReceiptToFile(receipt.toString());
}
private void saveReceiptToFile(String receiptText) {
try {
File dir = new File("receipts");
if (!dir.exists()) dir.mkdirs();
int receiptNum = Objects.requireNonNull(dir.list()).length + 1;
File file = new File(dir, "receipt" + receiptNum + ".txt");
try (PrintWriter writer = new PrintWriter(file)) {
writer.print(receiptText);
}
System.out.println("Receipt saved as: " + file.getName());
} catch (Exception e) {
System.out.println("Failed to save receipt: " + e.getMessage());
}
}
public void removeItemByName(String itemName) {
GroceryItem toRemove = null;
for (GroceryItem item : cart.keySet()) {
if (item.getName().equalsIgnoreCase(itemName)) {
toRemove = item;
break;
}
}
if (toRemove != null) {
cart.remove(toRemove);
System.out.println(itemName + " removed from cart.");
} else {
System.out.println("Item not found in cart.");
}
}
}