后缀表达式计算java

准备一个数字栈,一个运算符栈。大致的思路就是遇到,数字直接入数字栈,运算符看优先级进行处理,将要入运算符栈的运算符与栈顶的运算符进行比较,栈顶运算符优先级比较高的话,则把栈顶的运算符弹并且把数字栈的两个数字进行弹出,进行运算,并且把结果再次放到数字栈中,最后剩下的就是最终结果。如果运算符优先级比运算符栈顶的小,则把运算符进栈,最后把运算符都出栈

import java.util.Stack;

public class CD {
  //  StringBuffer buff=new StringBuffer();
    Stack out=new Stack<>();
    Stack chars=new Stack<>();
    //表达式输入,结果展示
    public static void main(String args[]){
        String source="(2+9)/3-5";
        String end=new CD().start(source);
       System.out.println(end);
    }
    
    //接收表达式,进行大致的处理
    public String start(String cource){
        chars.push('#');
        for(int i=0;i='0'&&i<='9'||i=='.'){
            return false;
        }
        return true;
    }
    public void doChar(char operation){//遇到运算符时的处理
        if(chars.peek()=='('){
            chars.push(operation);
            return;
        }
        if(operation==')'){//遇到了')'把所有直到'('为止出栈了
            while(!chars.isEmpty()&&chars.peek()!='('){
                doCalculation(chars.pop());
            }
            if(!chars.isEmpty()){
                chars.pop();
            }
            return;
        }
        if(operationLv(operation)>operationLv(chars.peek())){
            chars.push(operation);
        }else{
            doCalculation(chars.pop());
            chars.push(operation);
        }
    }
    public void doNum(StringBuffer num){//遇到数字时的处理
        out.push(num);
    }
    public void outStack(){//到表达式最后时将所有的运算符出栈
        while(!chars.isEmpty()&&chars.peek()!='#'){//每出一个运算符进行一次运算
            doCalculation(chars.pop());
        }
    }
    public void doCalculation(char chars){//将两个数值取出进行运算,并将结果再次放到栈中
        double b=Double.parseDouble(out.pop().toString());
        double a=Double.parseDouble(out.pop().toString());
        double c=0;
        switch (chars){
            case '+':
                c=a+b;
                out.push(new StringBuffer(Double.toString(c)));break;
            case '-':
                c=a-b;
                out.push(new StringBuffer(Double.toString(c)));break;
            case '*':
                c=a*b;
                out.push(new StringBuffer(Double.toString(c)));break;
            case '/':
                c=a/b;
                out.push(new StringBuffer(Double.toString(c)));break;
        }
    }
    public int operationLv(char operation){//给运算符设置优先级
        switch (operation){
            case '+':
            case'-':
                return 1;
            case'*':
            case'/':
                return 2;
            case'(':
            case')':
                return 3;
            default:
                return 0;
        }
    }

}

你可能感兴趣的:(后缀表达式计算java)