表达式求值(java实现)

package suanfaTest;

import java.util.Stack;

public class biaodashiTest02 {
    public String insetString(String expression){
        String reslut = "";
        for (int i = 0; i numberStack = new Stack();
        Stack operatorStack = new Stack();
        expression = insetString(expression);
        String[] tokens = expression.split(" ");
        for (String token:tokens){
            if (token.length() == 0){
                continue;
            }else if (token.trim().charAt(0) == '+'||token.trim().charAt(0) == '-' ){
                while (!operatorStack.isEmpty()&&(operatorStack.peek()=='+'||operatorStack.peek()=='-'||
                        operatorStack.peek()=='*'||operatorStack.peek()=='/')){
                    calculateExpression(numberStack,operatorStack);
                }
                operatorStack.push(token.charAt(0));
            }else if (token.trim().charAt(0) == '*'||token.trim().charAt(0) == '/' ){
                while (!operatorStack.isEmpty()&&(operatorStack.peek()=='*'||operatorStack.peek()=='/')){
                    calculateExpression(numberStack,operatorStack);
                }
                operatorStack.push(token.charAt(0));
            }else if (token.trim().charAt(0) == '('){
                operatorStack.push(token.charAt(0));
            }else if (token.trim().charAt(0) == ')'){
                while (operatorStack.peek()!='('){
                    calculateExpression(numberStack,operatorStack);
                }
                operatorStack.pop();//弹出'('
            }else {
                numberStack.push(Integer.parseInt(token.trim()));
            }
        }
        while (!operatorStack.isEmpty()){
            calculateExpression(numberStack,operatorStack);
        }
        int result = numberStack.peek();//这一步与numberStack.peek()作用相同
        return result;
    }

    public void calculateExpression(Stack numberStack,Stack operatorStack){
        char op = operatorStack.pop();//运算符栈中弹出一个运算符
        int op02 = numberStack.pop();//数字栈中弹出一个数字
        int op01 = numberStack.pop();//数字栈中再弹出一个数字
        if (op == '+'){
            numberStack.push(op01+op02);
        }else if (op == '-'){
            numberStack.push(op01-op02);
        }else if (op == '*'){
            numberStack.push(op01*op02);
        }else if (op == '/'){
            numberStack.push(op01/op02);
        }
    }
    public static void main(String args[]){
        biaodashiTest02 bs = new biaodashiTest02();
        String a = "1-(2*3+5)";
        int result = bs.operatorExpression(a);
        System.out.println(result);
    }

}

 

你可能感兴趣的:(算法)