This method has yet to be perfected, such as not judging if the divisor is 0 when doing division, and can also be extended, such as log, sin, operator precedence.
1 Public classEvaluate {2 3 Public Static voidMain (string[] args) {4String steam = "(1 + (2 + 3) * (4 * 5))";5 //String steam = "((1 + sqrt (5.0))/2.0)";6stack<string> Ops =NewStack<string>();7Stack<double> Vals =NewStack<double>();8 9string[] steams = Steam.split ("");Ten One for(inti=0; i<steams.length; i++) { A //reads the character, and if the operator presses it into the stack -String s =Steams[i]; - /*Char item = Steam.charat (i); the String s = string.valueof (item);*/ - - - if(S.equals ("(")) { + ; -}Else if(S.equals ("+")) { + Ops.push (s); A}Else if(S.equals ("-")) { at Ops.push (s); -}Else if(S.equals ("*")) { - Ops.push (s); -}Else if(S.equals ("/")) { - Ops.push (s); -}Else if(S.equals ("sqrt")) { in Ops.push (s); -}Else if(S.equals (")")) { to //If the character is ")" then the operator and operand are popped, the result is calculated and pressed into the stack +String op =Ops.pop (); - Doublev =Vals.pop (); the if(Op.equals ("+")) { *v = vals.pop () +v; $}Else if(Op.equals ("-")) {Panax Notoginsengv = vals.pop ()-v; -}Else if(Op.equals ("*")) { thev = vals.pop () *v; +}Else if(Op.equals ("/")) { Av = vals.pop ()/v; the}Else if(Op.equals ("sqrt")) { +v =math.sqrt (v); - } $ Vals.push (v); $}Else { - //If the character is neither an operator nor a parenthesis, it is pressed into the stack as a double value - Vals.push (double.parsedouble (s)); the } - }Wuyi System.out.println (Vals.pop ()); the } -}
A double stack arithmetic expression evaluation algorithm for stack practice--dijkstra