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