/** 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); } exp = exp.substring(1, exp.length() - 1); char op = EvaluatorUtilities.nextOperator(exp); int opIndex = EvaluatorUtilities.nextOperatorIndex(exp); String left = exp.substring(0, opIndex); String right = exp.substring(opIndex + 1); // Find answer for left, find answer for right, op them together if (op == '+') { return evaluate(left) + evaluate(right); } else if (op == '*') { return evaluate(left) * evaluate(right); } 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(" ", ""))); } } }