-
Notifications
You must be signed in to change notification settings - Fork 0
/
InterpreterExample.java
66 lines (54 loc) · 1.74 KB
/
InterpreterExample.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
package interpreter;
import java.util.HashMap;
import java.util.Map;
class ExpressionProcessor {
public Map<Character, java.lang.Integer> variables = new HashMap<>();
enum NextOp {
NOTHING, PLUS, MINUS
}
public static java.lang.Integer tryParse(String text) {
try {
return java.lang.Integer.parseInt(text);
} catch (NumberFormatException e) {
return null;
}
}
public int calculate(String expression) {
int current = 0;
NextOp nextOp = NextOp.NOTHING;
String[] parts = expression.split("(?<=[+-])");
for (String part : parts) {
String[] noOp = part.split("[+-]");
String first = noOp[0];
int value;
java.lang.Integer z = tryParse(first);
if (z != null) {
value = z.intValue();
} else if (first.length() == 1
&& variables.containsKey(first.charAt(0))) {
value = variables.get(first.charAt(0));
} else return 0;
switch (nextOp) {
case NOTHING:
current = value;
break;
case PLUS:
current += value;
break;
case MINUS:
current -= value;
break;
}
if (part.endsWith("+")) nextOp = NextOp.PLUS;
else if (part.endsWith("-")) nextOp = NextOp.MINUS;
}
return current;
}
}
public class InterpreterExample {
public static void main(String[] args) {
ExpressionProcessor ep = new ExpressionProcessor();
ep.variables.put('x', 5);
System.out.println(ep.calculate("1+x"));
}
}