带括号的中缀计算表达式转逆波兰表达式同时计算结果

import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CalculatorDemo {

    public static void main(String args[]){
        String expression = "1 + ( ( 2 + 3 ) * 4 ) - 5 ";
        Calculator c = new Calculator(expression);
        String s = c.transfertosuffix(c.expression);
        System.out.println(s);
        System.out.println("****************");
        String result = c.calculateResult(s);
        System.out.println("result="+result);
    }

}

class Calculator{
    String[] expression;
    public Calculator(String str){
        expression = str.split(" ");

    }
    public static HashMap<String, Integer> operWithPriority = new HashMap<String, Integer>();
    public static void getOper(){
        operWithPriority.put("+",1);
        operWithPriority.put("-",1);
        operWithPriority.put("*",2);
        operWithPriority.put("/",2);
        operWithPriority.put("%",2);
    }

    public double calculate(String num1,String num2, String oper){

        double num1double = Double.parseDouble(num2);
        double num2double = Double.parseDouble(num1);
        double result = 0;
        switch(oper){
            case "+": result = num1double+num2double; break;
            case "-": result = num1double-num2double; break;
            case "*": result = num1double*num2double; break;
            case "/": result = num1double/num2double; break;
            case "%": result = num1double%num2double; break;
        }
        return result;

    }

    public String calculateResult(String suffixStack){
        Mystack my= new Mystack(suffixStack.length());
        String[] strs = suffixStack.split(" ");
        String patterns = "^[0-9]+.?[0-9]*$";
        Pattern p = Pattern.compile(patterns);
        double result = 0 ;
        for(int i=0;i<strs.length;i++){
            String temp = strs[i];
            Matcher m = p.matcher(temp);
            if(m.matches()){
                my.push(temp);
            }else{
                String num1 = my.pop();
                String num2 = my.pop();
                result = calculate(num1, num2, temp);
                my.push(Double.toString(result));

            }

        }

        return my.pop();
    }

    public String transfertosuffix(String[] str){
        getOper();
        Mystack operstack= new Mystack(str.length);
        Mystack resultstack = new Mystack(str.length);
        for(int i=0;i<str.length;i++){
            String tempdata = str[i];
            if(operWithPriority.containsKey(tempdata)){
                if(operstack.isEmpty() || "[".equals(operstack.peek())||"(".equals(operstack.peek())) {
                    operstack.push(tempdata);
                }else {
                    String strintopstack = operstack.peek();
                    System.out.println(strintopstack);
                    int topstackPriority = operWithPriority.get(strintopstack);
                    int currentPriority = operWithPriority.get(tempdata);
                    while (currentPriority<=topstackPriority && !operstack.isEmpty() && !("[".equals(operstack.peek())||"(".equals(operstack.peek()))) {
                        strintopstack = operstack.pop();
                        resultstack.push(strintopstack);
                        if(!operstack.isEmpty() && !("[".equals(operstack.peek())||"(".equals(operstack.peek()))) {
                            System.out.println("I am here"+operstack.peek());
                            topstackPriority = operWithPriority.get(operstack.peek());
                        }
                    }
                    operstack.push(tempdata);
                }

            }else if(tempdata.equals("(") || tempdata.equals("[")){
                operstack.push(tempdata);
            }
            else if(tempdata.equals(")")){
                String opers = operstack.pop();
                while(!"(".equals(opers)){
                  try{
                      resultstack.push(opers);
                      opers = operstack.pop();

                  }catch(Exception e){
                      System.out.println("not matched small bracket (");
                      return "not appropriated expression,missing small brackets";
                  }


                }

            }
            else if(tempdata.equals("]")){
                String opers = operstack.pop();
                while(!"[".equals(opers)){
                    try{
                        resultstack.push(opers);
                        opers = operstack.pop();
                    }catch(Exception e){
                        System.out.println("not matched  bracket [");
                        return "not appropriated expression,missing  brackets";
                    }


                }
            }
            else{
                String pattern = "^[0-9]+.?[0-9]*$";
                Pattern p = Pattern.compile(pattern);
                Matcher matcher = p.matcher(tempdata);
                if(matcher.matches()){
                    resultstack.push(tempdata);
                }else{
                    throw new RuntimeException("not correct operator or numbers: "+tempdata);
                }
            }
        }
        while(!operstack.isEmpty()){
            resultstack.push(operstack.pop());
        }
        return resultstack.reverse();
    }
}
class Mystack{
    String[] stacks;
    int front;
    public Mystack(int len){
        stacks = new String[len];
        front = -1;
    }
    public boolean isFull(){
        return front==stacks.length-1;
    }
    public boolean isEmpty(){
        return front ==-1;
    }
    public void push(String value){
        if(isFull()){
            System.out.println("current stack is full");
            return;
        }
        front = front +1;
        stacks[front] = value;
    }

    public String pop(){
        if(isEmpty()){
            throw new RuntimeException("current stacks is empty");
        }
        String value = stacks[front];
        front = front-1;
        return value;
    }
    public String reverse(){
        StringBuilder str = new StringBuilder("");
        if(isEmpty()){
            System.out.println("curent stack is null");
            return null;
        }
        for(int i=0;i<front+1; i++){
//            System.out.print(stacks[i]+" ");
            str.append(stacks[i]+ " " );
        }
        return str.toString();
    }
    public String peek(){
        if(isEmpty()){
            throw new RuntimeException("current stacks is empty");
        }
        String value = stacks[front];
        return value;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值