使用中缀表达式实现加减乘除混合运算-查看文章

使用中缀表达式实现加减乘除混合运算

发表于:2023-12-26 10:54:02 分类:JAVA 阅读:166次

使用中缀表达式实现加减乘除混合运算。

import java.util.Stack;

/**
 * @author ERSREDMA
 * 中缀表达式
 */

public class Test {
    public static void main(String[] args) {
        ComputeNum computeNum = new ComputeNum("200+400+500*2+20/10-20002");
        Integer compute = computeNum.compute();
        System.out.println(compute);
    }
}
class ComputeNum{
    private Stack<Integer> numberStack = new Stack<>();
    private Stack<Character> operatorStack = new Stack<>();
    private String ex;

    public ComputeNum(String ex){
        this.ex = ex;
    }

    public Integer compute(){
        for (int i = 0; i < ex.length(); i++) {
            char c = ex.charAt(i);
            if(priority(c)>=0){
                //操作符
                if(!operatorStack.isEmpty()){
                    if(priority(c)>priority(operatorStack.peek())){
                        operatorStack.push(c);
                    }else{
                        Integer a = numberStack.pop();
                        Integer b = numberStack.pop();
                        Character op = operatorStack.pop();
                        numberStack.push(operatorNumber(a,b,op));
                        operatorStack.push(c);
                    }
                }else{
                    operatorStack.push(c);
                }
            }else{
                int endIndex = i;
                while (endIndex<ex.length()-1){
                    char next = ex.charAt(endIndex+1);
                    if(priority(next)>=0){
                        break;
                    }else {
                        endIndex++;
                    }
                }
                if(i == endIndex){
                    //只有一个数字
                    numberStack.push(c-'0');
                }else{
                    String substring = ex.substring(i, endIndex+1);
                    numberStack.push(Integer.parseInt(substring));
                    i = endIndex;
                }
            }
        }
        while (!operatorStack.isEmpty()){
            Character c = operatorStack.pop();
            Integer a = numberStack.pop();
            Integer b = numberStack.pop();
            numberStack.push(operatorNumber(a,b,c));
        }
        return numberStack.pop();
    }

    private int priority(char a){
        if(a=='*'||a=='/'){
            return 1;
        }
        if(a=='+'||a=='-'){
            return 0;
        }
        return -1;
    }

    private int operatorNumber(int a,int b,char operator){
        switch (operator){
            case '+':
                return a+b;
            case '-':
                return b-a;
            case '*':
                return a*b;
            case '/':
                return b/a;
        }
        throw new RuntimeException("错误的表达式!");
    }
}


关键词:java,算法


验证码: