-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathVendingMachineMenu.java
97 lines (91 loc) · 2.75 KB
/
VendingMachineMenu.java
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
import java.util.Scanner;
import java.io.IOException;
/**
A menu from the vending machine.
*/
public class VendingMachineMenu
{
private Scanner in;
private static Coin[] coins = { new Coin(0.05, "nickel"),
new Coin(0.1, "dime"),
new Coin(0.25, "quarter"),
new Coin(1, "dollar") };
/**
Constructs a VendingMachineMenu object
*/
public VendingMachineMenu()
{
in = new Scanner(System.in);
}
/**
Runs the vending machine system.
@param machine the vending machine
*/
public void run(VendingMachine machine)
throws IOException
{
boolean more = true;
while (more)
{
System.out.println("S)how products I)nsert coin B)uy A)dd product R)emove coins Q)uit");
String command = in.nextLine().toUpperCase();
if (command.equals("S"))
{
for (Product p : machine.getProductTypes())
System.out.println(p);
}
else if (command.equals("I"))
{
machine.addCoin((Coin) getChoice(coins));
}
else if (command.equals("R"))
{
System.out.println("Removed: $" + machine.removeMoney());
}
else if (command.equals("B"))
{
try
{
Product p = (Product) getChoice(machine.getProductTypes());
machine.buyProduct(p);
System.out.println("Purchased: " + p);
}
catch (VendingException ex)
{
System.out.println(ex.getMessage());
}
}
else if (command.equals("A"))
{
System.out.println("Description:");
String description = in.nextLine();
System.out.println("Price:");
double price = in.nextDouble();
System.out.println("Quantity:");
int quantity = in.nextInt();
in.nextLine(); // read the new-line character
machine.addProduct(new Product(description, price), quantity);
}
else if (command.equals("Q"))
{
more = false;
}
}
}
private Object getChoice(Object[] choices)
{
while (true)
{
char c = 'A';
for (Object choice : choices)
{
System.out.println(c + ") " + choice);
c++;
}
String input = in.nextLine();
int n = input.toUpperCase().charAt(0) - 'A';
if (0 <= n && n < choices.length)
return choices[n];
}
}
}