Dijkstraのデュアルスタックアルゴリズム式評価アルゴリズム


import java.util.Stack;

/**
 * Created by gary on 16-1-3.
 */
public class TestStack {
    public static void main(String[] args) {
        String expression = "(1+((2+3)*(4*5)))";
        Stack ops = new Stack<>();
        Stack vals = new Stack<>();
        for(int i = 0; i < expression.length(); i++) {
            char c = expression.charAt(i);
            if(c == '(');
            else if(c == '+') ops.push(c);
            else if(c == '-') ops.push(c);
            else if(c == '*') ops.push(c);
            else if(c == '/') ops.push(c);
            else if(c == ')') {
                char op = ops.pop();
                Double v = vals.pop();
                if(op == '+') v = vals.pop() + v;
                if(op == '-') v = vals.pop() - v;
                if(op == '*') v = vals.pop() * v;
                if(op == '/') v = vals.pop() / v;
                vals.push(v);
            }
            else {
                vals.push(Double.parseDouble(String.valueOf(c)));
            }
        }
        System.out.println(vals.pop());
    }
}