-
Notifications
You must be signed in to change notification settings - Fork 351
Expand file tree
/
Copy pathVendingMachineController.java
More file actions
80 lines (67 loc) · 2.58 KB
/
Copy pathVendingMachineController.java
File metadata and controls
80 lines (67 loc) · 2.58 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
package vendingmachine.controller;
import vendingmachine.model.Balance;
import vendingmachine.model.Product;
import vendingmachine.model.Validator;
import vendingmachine.view.InputView;
import vendingmachine.view.OutputView;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static vendingmachine.model.Validator.validateProduct;
public class VendingMachineController {
private static Balance balance;
private static Map<String, Product> products;
private static int amountOfInput;
public void setVendingMachine() {
balance = new Balance(InputView.readBalance());
OutputView.printBalanceCoin(balance.createCoin());
saveProducts();
amountOfInput = InputView.readAmountOfInput();
OutputView.printAmountOfInput(amountOfInput);
}
public void runVendingMachine() {
while (canBuy()) {
buy();
OutputView.printAmountOfInput(amountOfInput);
}
OutputView.printChange(balance.calculateChangeCoin(amountOfInput));
}
private boolean canBuy() {
List<Integer> leftProductsPrice = new ArrayList<Integer>();
for (Map.Entry<String, Product> entry : products.entrySet()) {
if (entry.getValue().stockIsLeft()) {
leftProductsPrice.add(entry.getValue().getPrice());
}
}
if (leftProductsPrice.isEmpty()) {
return false;
}
return amountOfInput >= leftProductsPrice.stream().mapToInt(Integer::intValue).min().getAsInt();
}
public void saveProducts() throws IllegalArgumentException {
products = new HashMap<>();
try {
String[] str = InputView.readProductInfo().split(";");
for (String s : str) {
String[] productInfo = s.substring(1, s.length() - 1).split(",");
validateProduct(productInfo, products);
products.put(productInfo[0], new Product(productInfo[1], productInfo[2]));
}
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
saveProducts();
}
}
private void buy() {
try {
String buyingProduct = InputView.readBuyingProduct();
Validator.validateBuyingProduct(buyingProduct, products, amountOfInput);
amountOfInput -= products.get(buyingProduct).getPrice();
products.get(buyingProduct).reduceAmount();
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
buy();
}
}
}