Example: 3 + 4 * 3 + (5 - 1)#
Reference blog: https://blog.csdn.net/qq_20009015/article/details/83870474
Solutions:
- The difficulty of this problem lies in how to distinguish priorities and realize four operations
- First, define two stacks: the operand stack is used to store operands, and the operator stack is used to store operators
- The key point of expression evaluation is to calculate the priority of symbols. When the priority of the current symbol is higher than that of the top of the stack, it will directly enter the stack; if the priority of the current symbol is lower than that of the top of the stack, it will calculate the two elements of the top of the current operand stack; if it is equal to, it will exit the stack
- See code for definition of priority
Code:
package practise; import java.io.IOException; import java.util.Stack; public class EvaluateExpression { // Define two stacks private static Stack<Character> stackOpr = new Stack<>(); private static Stack<Integer> stackNum = new Stack<>(); // Evaluation expression public static void main(String [] args) throws IOException { char c = (char)System.in.read(); stackOpr.push('#'); while(c != '#' || stackOpr.peek() != '#'){ if(isNum(c)){ stackNum.push(c - 48); c = (char)System.in.read(); }else{ switch(isPrior(c)){ case '<': int a = stackNum.pop(); int b = stackNum.pop(); stackNum.push(operation(b, a, stackOpr.pop())); break; case '>': stackOpr.push(c); c = (char)System.in.read(); break; case '=': stackOpr.pop(); c = (char)System.in.read(); break; } } } System.out.println(stackNum.pop()); } // Determine the priority of characters static char isPrior(char c){ char c1 = stackOpr.peek(); if(c == '+' || c == '-'){ if(c1 == '+' || c1 == '-' || c1 == '*' || c1 == '/' || c1 == ')') return '<'; if(c1 == '(' || c1 == '#') return '>'; } if(c == '*' || c == '/'){ if(c1 == '*' || c1 == '/' || c1 == ')') return '<'; if(c1 == '+' || c1 == '-' || c1 == '#' || c1 == '(') return '>'; } if(c == '('){ return '>'; } if(c == ')'){ if(c1 == '(') return '='; else return '<'; } if(c == '#'){ if(c1 == '#') return '='; else return '<'; } return 0; } // Evaluate current expression static int operation(int a, int b, char c){ switch(c){ case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; } return 0; } // Judge whether it is a number static boolean isNum(char c){ if(c == '+' || c == '-' || c == '*' || c == '/' || c == '(' || c == ')' || c =='#'){ return false; } return true; } }