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
/** This class provides a method to evaluate fully parenthesized mathematical
* expressions.
*
* @author Adam Blank
*/
public class IterativeEvaluator {
/** Evaluates fully parenthesized mathematical expressions that use addition
* and multiplication. */
public static int evaluate(String exp) throws NotImplementedException {
int lastOpen = -1;
while (!EvaluatorUtilities.isNumber(exp)) {
int nextClose = 0;
/* Find the next chunk surrounded by parentheses. */
while (exp.charAt(nextClose) != ')') {
if (exp.charAt(nextClose) == '(') {
lastOpen = nextClose;
}
nextClose++;
}
String subExp = exp.substring(lastOpen + 1, nextClose);
/* Split the string up by the op */
int opIndex = EvaluatorUtilities.nextOperatorIndex(subExp);
String left = subExp.substring(0, opIndex);
String right = subExp.substring(opIndex + 1, subExp.length());
char op = EvaluatorUtilities.nextOperator(subExp);
String result = "";
if (op == '+') {
result = "" + (Integer.parseInt(left) + Integer.parseInt(right));
}
else if (op == '*') {
result = "" + (Integer.parseInt(left) * Integer.parseInt(right));
}
else {
throw new NotImplementedException();
}
exp = exp.substring(0, lastOpen) + result + exp.substring(nextClose + 1);
}
return Integer.parseInt(exp);
}
public static void main(String[] args) throws NotImplementedException {
String[] exps = {"(1+(2*4))", "((1+1)*(2*(3+3)))"};
for (int i = 0; i < exps.length; i++) {
System.out.println(exps[i] + " = " + evaluate(exps[i].replaceAll(" ", "")));
}
}
}