-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathShoppingBasket.java
More file actions
74 lines (60 loc) · 2.23 KB
/
ShoppingBasket.java
File metadata and controls
74 lines (60 loc) · 2.23 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
70
71
72
73
74
import java.util.ArrayList;
import java.util.List;
public class ShoppingBasket {
private List<BasketItem> items;
public ShoppingBasket() {
items = new ArrayList<>();
}
public void addItem(Product product, int quantity) {
if (quantity <= 0) {
System.out.println("Quantity must be a positive number.");
return;
}
boolean itemExists = false;
for (BasketItem item : items) {
if (item.getProduct().getProductId() == product.getProductId()) {
item.setQuantity(item.getQuantity() + quantity);
itemExists = true;
break; // Looptan ürün eklendiğinde çık
}
}
if (!itemExists) {
// Yeni product yoksa sepete ekle
items.add(new BasketItem(product, quantity));
}
}
public void removeItem(Product product, int quantity) {
for (BasketItem item : items) {
if (item.getProduct().getProductId() == product.getProductId()) {
if (item.getQuantity() < quantity) {
System.out.println("You're trying to remove more than the available quantity.");
return;
}
item.setQuantity(item.getQuantity() - quantity);
if (item.getQuantity() == 0) {
items.remove(item);
}
return;
}
}
System.out.println("This product is not in your basket.");
}
public void displayBasket() {
if (items.isEmpty()) {
System.out.println("Your basket is empty.");
return;
}
for (BasketItem item : items) {
Product product = item.getProduct();
double totalPrice = item.getQuantity() * product.getPrice();
System.out.printf("Product: %s\nQuantity: %d\nUnit Price: $%.2f\nTotal Price: $%.2f\n",
product.getName(),
item.getQuantity(),
product.getPrice(),
totalPrice);
}
}
public List<BasketItem> getItems() {
return items;
}
}