SoFunction
Updated on 2025-03-06

How to calculate the value of an expression using inverse Polish (suffix expression) in Java

question

In actual projects, the return result of the interface needs to be processed, and arithmetic expression is obtained according to the return result field in the configuration, combined with the arithmetic operator (+ - * /) and left and right brackets, and the value is calculated and returned.

How to solve it

  • After obtaining the return value of the interface, you can get a specific infix expression
  • Convert an infix expression to a suffix expression (inverse Polish)
  • Calculate the value of the suffix expression

Code

Operator enumeration class

public enum Operator {

    ADD(30, '+'),
    SUB(30, '-'),
    MUL(40, '*'),
    DIV(40, '/'),
    LEFT(0, '('),
    RIGHT(0, ')');

    static {
        map = (values()).collect(toMap(::getSymbol, e -> e));
    }

    private final int priority;
    private final char symbol;

    private static final Map<Character, > map;

    Operator(Integer priority, Character symbol) {
         = priority;
         = symbol;
    }

    public Character getSymbol() {
        return ;
    }

    //Return the corresponding priority number    public static int getPriority(Character symbol) {
         operator = (symbol);
        assert (operator);
        return ;
    }

    public static boolean notRightBracket(Character symbol) {
         operator = (symbol);
        if ((operator)) {
            return false;
        }
        return !(RIGHT);
    }

    public static boolean isOperator(Character symbol) {
         operator = (symbol);
        if ((operator)) {
            return false;
        }
        switch (operator) {
            case ADD:
            case SUB:
            case MUL:
            case DIV: return true;
            default: return false;
        }
    }
}

Expression tool class

public class ExprUtils {

    /*Judge whether the infix expression is legal*/
    public static boolean expressionCheck(String str) {
        Deque<Character> stack = new LinkedList<>();
        //Illegal situation 1: brackets do not match        for(char ch : ()) {
            if(ch == '(') {
                (ch);
            }

            if(ch == ')') {
                if(()) {
                    return false;
                }
                ();
            }
        }
        if (!()) {
            return false;
        }

        //Illegal situation 2: The left and right elements of the operator are illegal        for(int i = 0 ; i < () ; i++) {
            //Judge whether '-' is a negative symbol first            if('-' == (i)) {
                if( 0 == i || ((i - 1))) //If - in the first position or before it is +-*/(, it must be used as a negative symbol rather than an operator                    i++;
            }
            if(((i))) {
                if( 0 == i || () - 1 == i)
                    return false;
                if( ((i - 1)) || ((i + 1)) )
                    return false;
                if( '(' == (i - 1) || ')' == (i + 1) )
                    return false;
            }
        }

        //Illegal case 3: The left bracket and the closing bracket are adjacent, examples: a+() and (a+b)(a+b)        for(int i = 0 ; i < () ; i++) {
            if((i) =='(' && i + 1 < () && (i + 1) == ')')
                return false;
            if((i) == ')' && i + 1 < () && (i + 1) == '(')
                return false;
        }
        return true;
    }

    /**
      * Convert an infix expression to a suffix expression
      *
      * @param exp Infix expression
      * @return suffix expression
      */
    public static List<String> parseExpression(String exp) {

        Deque<Character> operation = new LinkedList<>();
        List<String> target = new ArrayList<>();

        for (int i = 0; i < (); i++) {
            if((((i) == '-' || (i) == '+') && (i == 0 || ((i - 1))))
                    || ((i)) ) {
                // If it is a positive sign, you don't need to add it. Negative signs or numbers themselves must be added.                StringBuilder tempStr = new StringBuilder((i) != '+' ? (i, i + 1) : "");
                while (i + 1 <  () && ((i + 1))) {
                    ((++i));
                }
                (());
            } else {
                if ('(' == (i)) {
                    ((i));
                } else if (')' == (i)) {
                    while ('(' != ()) {
                        (().toString());
                    }
                    ();
                } else {
                    while (!()
                            && (()) >= ((i))) {
                        (().toString());
                    }

                    ((i));
                }
            }
        }

        while (!()) {
            (().toString());
        }

        return target;
    }

    /**
      * Calculate the suffix expression
      *
      * @param list suffix expression
      * @return Calculation result
      */
    public static int calculate(List<String> list) {
        Stack<Integer> stack = new Stack<>();// Create a stack        for (String item : list) {
            if (("^-?\\d+(\\.\\d+)?$")) { //Match multi-digit numbers using regular expression                ((item));
            } else {
                int num2 = ();	// pop out two numbers, calculate, and then enter the stack                int num1 = ();
                int res;
                switch (item) {
                    case "+": res = num1 + num2; break;
                    case "-": res = num1 - num2; break;
                    case "*": res = num1 * num2; break;
                    case "/": res = num1 / num2; break;
                    default: throw new RuntimeException("The operator is wrong");
                }
                (res);
            }

        }

        return ();
    }
}

Test class

class ExprUtilsTest {

    @Test
    void calculate() {
        String infixExpression = "-6+((-2)+(2+4))";
        if (!(infixExpression)) {
            ("Expression is illegal");
        } else {
            ("The infix expression is:" + infixExpression);
            List<String> calculateExpression = (infixExpression);
            ("The suffix expression is:" + calculateExpression);
            ("Answer=%d", (calculateExpression));
        }
    }
}

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.