This repository has been archived by the owner on Feb 15, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
MainCLI.java
82 lines (72 loc) · 2.5 KB
/
MainCLI.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
package mediumjavafxmvcexample;
import java.util.Scanner;
import java.util.regex.Pattern;
import mediumjavafxmvcexample.SlotMachine.ROUTES;
public class MainCLI {
private final SlotMachine smOne;
private final SlotMachine smTwo;
private final Pattern commands = Pattern.compile(
"^machine (1|2) select route (1|2)$"
);
private final Pattern quitCommands = Pattern.compile(
"^(quit|exit|kill|stop)$"
);
public MainCLI(SlotMachine one, SlotMachine two) {
smOne = one;
smTwo = two;
}
public void runCommandLine() {
System.out.println("Welcome. Type in a command with the following syntax:\n"
+ "\tmachine [1 2] select route [1 2]"
+ "\n type one of [quit exit kill stop] to exit"
);
try (Scanner in = new Scanner(System.in)) {
while (true) {
// cleanse input
String input = in
.nextLine()
.trim()
.toLowerCase();
if (commands.matcher(input).matches()) {
processCommand(input);
dumpState();
} else if (quitCommands.matcher(input).matches()) {
System.exit(0);
} else {
System.out.println("Command not recognize");
}
}
}
}
private void processCommand(String input) {
// tokenize each word of the command
String[] tokens = input.split(" ");
// use reference to proper slot machine based of fof input token
SlotMachine sm;
if ("1".equals(tokens[1])) {
sm = smOne;
} else {
sm = smTwo;
}
switch (tokens[2]) {
case "select":
// determine which route was requested
ROUTES route;
if ("1".equals(tokens[4])) {
route = SlotMachine.ROUTES.ROUTE1;
} else {
route = SlotMachine.ROUTES.ROUTE2;
}
sm.setSelectedRoute(route);
break;
default:
System.out.println("Problem processing command. Try again");
}
}
private void dumpState() {
String msg = "Current State: \n"
+ "machine 1:\t" + smOne.getSelectedRoute()
+ "\nmachine 2:\t" + smTwo.getSelectedRoute();
System.out.println(msg);
}
}