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
/** This class provides a method to evaluate fully parenthesized mathematical
* expressions.
*
* @author Adam Blank
*/
public class Evaluator {
/** Evaluates fully parenthesized mathematical expressions that use addition
* and multiplication. */
public static int evaluate(String exp) throws NotImplementedException {
if (EvaluatorUtilities.isNumber(exp)) {
return Integer.parseInt(exp);
}
else {
exp = exp.substring(1, exp.length() - 1);
int nextOpIdx = EvaluatorUtilities.nextOperatorIndex(exp);
char op = EvaluatorUtilities.nextOperator(exp);
String left = exp.substring(0, nextOpIdx);
String right = exp.substring(nextOpIdx + 1);
int resultLeft = evaluate(left);
int resultRight = evaluate(right);
if (op == '+') {
return resultLeft + resultRight;
}
else if (op == '*') {
return resultLeft * resultRight;
}
else {
throw new NotImplementedException();
}
}
}
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(" ", "")));
}
}
}