-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVendingMachine.java
More file actions
79 lines (67 loc) · 2 KB
/
VendingMachine.java
File metadata and controls
79 lines (67 loc) · 2 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
75
76
77
78
79
import java.util.ArrayList;
/**
* A vending machine.
*/
public class VendingMachine {
private ArrayList<Product> products;
public CoinSet coins;
public CoinSet currentCoins;
/**
* Constructs a VendingMachine object.
*/
public VendingMachine() {
products = new ArrayList<Product>();
coins = new CoinSet();
currentCoins = new CoinSet();
}
public Product[] getProductTypes() {
int output = products.size();
Product[] outputProducts = new Product[output];
for (int i = 0; i < output; i++) {
outputProducts[i] = products.get(i);
}
return outputProducts;
}
public void addProduct(Product product, int quantity) {
if (getProduct(product) == null) {
products.add(product);
product.setQuantity(quantity);
} else {
product = getProduct(product);
product.setQuantity(product.getQuantity() + quantity);
}
}
public void buyProduct(Product p) {
if (p.getPrice() >= currentCoins.getAmount()) {
p.setQuantity(p.getQuantity() - 1);
currentCoins = new CoinSet();
if (p.getQuantity() == 0) {
products.remove(p);
}
} else {
throw new VendingException("Insufficient funds, please insert more money");
}
}
public void addCoin(Coin choice) {
currentCoins.addCoin(choice);
}
public String removeMoney() {
StringBuilder str = new StringBuilder();
for (Coin c : currentCoins.getSet()) {
str.append(c.getName() + ", ");
}
if (!str.isEmpty()) {
str.delete(str.length() - 1, str.length() - 1);
}
currentCoins = new CoinSet();
return str.toString();
}
private Product getProduct(Product p) {
for (Product prod : products) {
if (prod.equals(p)) {
return prod;
}
}
return null;
}
}