Evaluator.java 1.38 KB
/** 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(" ", "")));
        }
    }
}