java逆波兰式进行四则运算

输入一个运算表达式,利用逆波兰式输出运算结果

package 逆波兰式;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.Stack;
import java.util.Scanner;

public class ReversePolish {


    public ReversePolish() {
    }

    /**
     * 后缀式计算结果
     * @param arr
     * @return
     */
    public double suffixCalculate(String arr){
        double result = 0;
        arr = infixTurnSuffix(arr);//调用函数进行中缀式转后缀式,并将数字标记
        int p = 0;
        Stack<String> stack = new Stack<>();
        for (int i = 0; i < arr.length(); i++) {
            if (isNumber(arr.charAt(i))) {//判断是否为数字
                while (arr.charAt(i) != ',') {//如果是多位数进行多位数输出
                    p = p * 10 + Character.getNumericValue(arr.charAt(i++));
                }
                stack.push(String.valueOf(p));//将数字入栈
                p = 0;
            } else if (isOperator(arr.charAt(i))) {//如果为运算符进行计算
                String num1 = stack.pop();//记录栈头数字,并出栈
                String num2 = stack.pop();//记录栈头数字,并出栈
                String num = num2 + arr.charAt(i) + num1;//将要进行的运算形成表达式
                //网上找的方法,暂时不理解
               try {
                   ScriptEngineManager manager = new ScriptEngineManager();
                   ScriptEngine engine = manager.getEngineByName("js");
                   Object sum = engine.eval(num);
                   stack.push(sum.toString());
               }catch (ScriptException e){
                   e.printStackTrace();
               }
            }
        }
        result = Double.parseDouble(stack.pop());//将运算结果转为double类型,并返回
        return result;
    }

    /**
     * 将中缀式转为后缀式
     * @param arr
     * @return
     */
    private String infixTurnSuffix(String arr) {
        Stack<Character> stack = new Stack<>();
        String arr1 = new String();
        for (int i = 0; i < arr.length(); i++) {
            if (arr.charAt(i) == '(') {//如果是左括号直接入栈
                stack.push(arr.charAt(i));
            } else if (isOperator(arr.charAt(i))) {//判断是否为运算符
                char cur = arr.charAt(i);
                if (stack.empty()) {//如果栈为空直接入栈
                    stack.push(cur);
                } else if (stack.peek() == '(' || compare(cur) >= compare(stack.peek())) {//栈头不为左括号,或者当前运算符优先级大于等于栈头运算符,进行入栈
                    stack.push(cur);
                } else {//如果当前运算符优先级小于栈头运算符,进行出栈操作,然后将当前运算符进行入栈操作
                    for (int j = 0; j <= stack.size(); j++) {
                        char ch = stack.pop();
                        arr1 += ch;
                        //当前运算符进行入栈操作
                        if (stack.isEmpty()) {
                            stack.push(cur);
                            break;
                        } else if (compare(cur) > compare(stack.peek())) {
                            stack.push(cur);
                            break;
                        }
                    }
                }
            } else if (arr.charAt(i) == ')') {//如果当前字符为右括号,进行出栈操作,直到遇见左括号
                for (int j = 0; j <= stack.size(); j++) {
                    char cur = stack.pop();
                    if (cur == '(') {
                        break;
                    } else {
                        arr1 += cur;
                    }
                }
            } else {//如果当前字符为数字,直接输出进行字符串拼接
                arr1 += arr.charAt(i);
                if (i == arr.length() - 1 || !isNumber(arr.charAt(i + 1))) {//如果当前字符的下一个字符不为数字进行标记代表一个数
                    arr1 += ',';
                }
            }
        }
        while (!stack.empty()) {//将栈中剩余的字符进行字符串拼接
            arr1 += stack.pop();
        }
        return arr1;//返回后缀表达式
    }

    /**
     * 判断是否为数字
     * @param charAt
     * @return
     */
    private boolean isNumber(char charAt) {
        if (charAt >= 48 && charAt <= 57) {
            return true;
        }
        return false;
    }

    /**
     * 判断是否为运算符
     * @param charAt
     * @return
     */
    private boolean isOperator(char charAt) {
        if (charAt == '+' || charAt == '-' || charAt == '*' || charAt == '/')
            return true;
        return false;
    }

    /**
     * 返回优先级
     * @param charAt
     * @return
     */
    private int compare(char charAt) {
        if (charAt == '+' || charAt == '-') {
            return 1;
        } else if (charAt == '*' || charAt == '/') {
            return 2;
        } else {
            return 3;
        }
    }
}
public class TestDemo {
    public static void main(String[] args)  {
        ReversePolish polish = new ReversePolish();
        Scanner scanner = new Scanner(System.in);
        String arr = scanner.next();
        //9+(3-1)+3*10/2
        double x = polish.suffixCalculate(arr);
        System.out.println(x);
    }
}

你可能感兴趣的:(java逆波兰式进行四则运算)