逆波兰表示法Java

package org.plkong;

import java.util.Stack;

public class Calculate {

    /**
     * @param args
     */
    public static void main(String[] args) {
        Calculate calculate = new Calculate();
        System.out.println(calculate.calculate("5 1 2+4*+3-"));
    }
   
    public double calculate(String rpn) {
        Stack<String> calStack = new Stack<String>();
        rpn = rpn.replace("+", " + ");
        rpn = rpn.replace("-", " - ");
        rpn = rpn.replace("*", " * ");
        rpn =rpn.replace("/", " / ");
        rpn =rpn.replace("  ", " ");
        String[] rpns = rpn.split(" ");
        for (String rp : rpns) {
            if (isOperator(rp)) {
                String cal1 = calStack.pop();
                String cal2 = calStack.pop();
                calStack.push(calculate(cal2, cal1, rp));
            } else {
                calStack.push(rp);
            }
        }
        return Double.parseDouble(calStack.pop());
    }
   
    public boolean isOperator(String op) {
        if (op.equals("+")) return true;
        if (op.equals("-")) return true;
        if (op.equals("*")) return true;
        if (op.equals("/")) return true;
       
        return false;
    }
   
    public String calculate(String cal1, String cal2, String op) {
        double cal_1 = Double.parseDouble(cal1);
        double cal_2 = Double.parseDouble(cal2);
       
        if (op.equals("+")) return String.valueOf(cal_1 + cal_2);
        if (op.equals("-")) return String.valueOf(cal_1 - cal_2);
        if (op.equals("*")) return String.valueOf(cal_1 * cal_2);
        if (op.equals("/")) return String.valueOf(cal_1 / cal_2);
       
        return null;
    }
}

 

你可能感兴趣的:(java)