forked from AllenDowney/ThinkJavaCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathVendingMachine.java
More file actions
117 lines (94 loc) · 2.03 KB
/
VendingMachine.java
File metadata and controls
117 lines (94 loc) · 2.03 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
public class VendingMachine
{
private int quarters;
private int dimes;
private int nickels;
public VendingMachine()
{
quarters = 0;
dimes = 0;
nickels = 0;
}
public void addQuarter()
{
quarters++;
}
public void addDime()
{
dimes++;
}
public void addNickel()
{
nickels++;
}
public int getCentsEntered()
{
int cents = 0;
cents += 25 * quarters;
cents += 10 * dimes;
cents += 5 * nickels;
return cents;
}
public boolean buyItem()
{
final int ITEM_COST = 50;
boolean itemBought;
if (getCentsEntered() >= ITEM_COST)
{
spendAmount(ITEM_COST);
itemBought = true;
}
else
{
itemBought = false;
}
return itemBought;
}
private void spendAmount(int amount)
{
int remainingAmount = amount;
int maxQuarters = remainingAmount / 25;
if (quarters >= maxQuarters)
{
remainingAmount -= maxQuarters * 25;
quarters -= maxQuarters;
}
else
{
remainingAmount -= quarters * 25;
quarters = 0;
}
int maxDimes = remainingAmount / 10;
if(dimes >= maxDimes)
{
remainingAmount -= maxDimes * 10;
dimes -= maxDimes;
}
else
{
remainingAmount -= maxDimes * 10;
dimes = 0;
}
int maxNickels = remainingAmount / 25;
if(nickels >= maxNickels)
{
nickels -=maxNickels;
}
else
{
nickels =0;
}
}
public int extractChange()
{
int change = getCentsEntered();
quarters = 0;
dimes = 0;
nickels = 0;
return change;
}
public String toString()
{
return "Vending Machine " + quarters + ":" + dimes + ":" + nickels + ":" + getCentsEntered();
}
}