Suffix expression Calculation
/*** Suffix expression calculation ** use stack to save the result ** 1. check each character in the suffix expression one by one from left to right * 2. when a number is pushed directly into the stack * 3. when an operator is encountered, two numbers will pop up from the stack for calculation, and the result will be kept in the stack. If the operator is/,-or ^, then the pop-up number is the first operation Number * 4. the final result is retained in the stack **/import java. util. stack; public class calc {public double calculate (String postfix) {Stack
Sk = new Stack
(); Char [] ch = postfix. toCharArray (); for (int I = 0; I
Sk, Character ch) {switch (ch + 0) {case '+ 0: sk. push (sk. pop () + sk. pop (); break; case '-' + 0: double tmp = sk. pop (); sk. push (sk. pop ()-tmp); break; case '*' + 0: sk. push (sk. pop () * sk. pop (); break; case '/' + 0: double temp = sk. pop (); sk. push (sk. pop ()/temp); break; case '^' + 0: double tp = sk. pop (); sk. push (Math. pow (sk. pop (), tp); break; case '%' + 0: double mp = sk. pop (); sk. push (sk. pop () % mp); break; default: throw new RuntimeException ();}}} // test Input 6*2 + (2 ^ 2 + 3*2/(3-1) ^ 2) * (3-1) Output 23.0