A double stack arithmetic expression evaluation algorithm for stack practice--dijkstra

Source: Internet
Author: User
Tags arithmetic

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.