Java implementation of arbitrary arithmetic expression evaluation algorithm _c language

Source: Internet
Author: User
Tags arithmetic

The example of this article describes the Java implementation of arbitrary arithmetic expression evaluation algorithm. Share to everyone for your reference. The specific analysis is as follows:

This program is used to compute arbitrary arithmetic expressions. The result of 4 * (10 + 2) + 1 should be 49.
Algorithm Description:

1. First define operator precedence. We use a

Map<string, Map<string, string>>

To save the priority table. This allows us to compute the precedence of the two operators in the following way:

/**
 * look-up table gets OP1 and OP2 priority
 * @param OP1 operator 1
 * @param OP2 operator 2
 * @return ">", "<" or "="
* * Public String priority (String OP1, String op2) {return
 prioritymap.get (OP1). get (OP2);

2. Scan the expression string, each time read into a token for processing.

Use two secondary stacks: Optstack is used to save the operator, Numstack is used to save the operand. We use ' # ' as the starting and result marker of an expression.

Read a token, if it is a number, then press into the Numstack stack;

If it is an operator, the top element a of the optstack stack is removed, and a is compared to the token.

If A < token, the token is pressed into the optstack stack.

If a = token, then token and a are a pair of parentheses, and the stack top element of the optstack stack pops up.

If A > token, the 2 operands are popped from the Numstack, 1 operators are popped from the optstack, and the results are computed.

When the Optstrack stack is empty (that is, the top element of the stack is ' # '), the stack top element of the Numstack stack is the value of the expression.

Algorithm implementation:

/** * Arithmetic expression evaluation. * 3 + 4 * 12 results for @author WHF * * */public class EvaluateExpression {//Operator precedence relation table private map<string, map<st
 Ring, string>> prioritymap = new hashmap<string, map<string, string>> ();
 Private linkedstack<string> Optstack = new linkedstack<string> ();
 operator Stack private linkedstack<double> numstack = new linkedstack<double> (); Operand stack/** * calculation expression * @param exp arithmetic expression, each symbol must be separated by a space * @return/public double Calcualte (String exp) {Strin
  Gtokenizer st = new StringTokenizer (exp);
   while (St.hasmoretokens ()) {String token = st.nexttoken ();
  Process (token);
 return Numstack.pop ();
  /** * Reads a symbolic string. * If it's a number, then press into Numstack * If it is an operator, the optstack stack top element is compared to the operator precedence * If the top element of the stack is low priority, the operator is pushed into the optstack stack, and if the same, the left parenthesis is popped, and if it is high, then 2 digits are removed. Takes out an operator to perform the calculation and then presses the result into the numstack stack * @param token/private void process (String token) {While false = #. Equals (opt Stack.gettop ()) | | false = = Token.equals ("#")) {//token is nUmeric if (true = = Isnumber (token)) {Numstack.push (double.parsedouble (token));
        Break
        Token is operator} else {String priority = Priority (Optstack.gettop (), token);
         if ("<". Equals (priority)) {Optstack.push (token);
        Break
         else if ("=". Equals (priority)) {Optstack.pop ();
        Break
          else {Double res = calculate (Optstack.pop (), Numstack.pop (), Numstack.pop ());
        Numstack.push (RES);  /** * Execute arithmetic * @param opt * @param n1 * @param n2 * @return/private double calculate (String
  OPT, double n1, double n2 {if ("+". Equals (opt)) {return n2 + N1;
  else if ("-". Equals (opt)) {return n2-n1;
  else if ("*". Equals (opt)) {return N2 * N1;
  else if ("/". Equals (opt)) {return n2/n1;
  else {throw new RuntimeException ("Unsupported operator:" + opt);
 }/** * Checks whether a string is a number * @param token * @return * * Private Boolean Isnumber (String token) {int LEN = Token.length ();
   for (int ix = 0; ix < LEN; ++ix) {Char ch = token.charat (ix); Skip decimal if (ch = = '. ')
   {continue;
   } if (false = = Isnumber (ch)) {return false;
 } return true; /** * Check whether a character is a number * @param ch * @return/private Boolean isnumber (char ch) {if (ch >= ' 0 ' && C
  H <= ' 9 ') {return true;
 return false; /** * look-up table gets OP1 and OP2 priority * @param OP1 operator 1 * @param OP2 operator 2 * @return ">", "<" or "=" */public String PR
 Iority (String op1, String op2) {return prioritymap.get (OP1). get (OP2);
  /** * Construct method, initialize priority table/public evaluateexpression () {//Initialize stack Optstack.push ("#");
  Initialize priority table//+ map<string, string> subMap = new hashmap<string, string> ();
  Submap.put ("+", ">");
  Submap.put ("-", ">");
  Submap.put ("*", "<");
  Submap.put ("/", "<");
  Submap.put ("(", "<"); SubmAp.put (")", ">");
  Submap.put ("#", ">");
  Prioritymap.put ("+", SUBMAP);
  -SubMap = new hashmap<string, string> ();
  Submap.put ("+", ">");
  Submap.put ("-", ">");
  Submap.put ("*", "<");
  Submap.put ("/", "<");
  Submap.put ("(", "<");
  Submap.put (")", ">");
  Submap.put ("#", ">");
  Prioritymap.put ("-", SUBMAP);
  * SubMap = new hashmap<string, string> ();
  Submap.put ("+", ">");
  Submap.put ("-", ">");
  Submap.put ("*", ">");
  Submap.put ("/", ">");
  Submap.put ("(", "<");
  Submap.put (")", ">");
  Submap.put ("#", ">");
  Prioritymap.put ("*", SUBMAP);
  /SubMap = new hashmap<string, string> ();
  Submap.put ("+", ">");
  Submap.put ("-", ">");
  Submap.put ("*", ">");
  Submap.put ("/", ">");
  Submap.put ("(", "<");
  Submap.put (")", ">");
  Submap.put ("#", ">");
  Prioritymap.put ("/", SUBMAP);
  (SubMap = new hashmap<string, string> ();
  Submap.put ("+", "<"); Submap.pUT ("-", "<");
  Submap.put ("*", "<");
  Submap.put ("/", "<");
  Submap.put ("(", "<");
  Submap.put (")", "=");
  Submap.put ("#", ">");
  Prioritymap.put ("(", SUBMAP);
  ) SubMap = new hashmap<string, string> ();
  Submap.put ("+", ">");
  Submap.put ("-", ">");
  Submap.put ("*", ">");
  Submap.put ("/", ">");
  Submap.put ("(", "<");
  Submap.put (")", ">");
  Submap.put ("#", ">");
  Prioritymap.put (")", SubMap);
  # subMap = new hashmap<string, string> ();
  Submap.put ("+", "<");
  Submap.put ("-", "<");
  Submap.put ("*", "<");
  Submap.put ("/", "<");
  Submap.put ("(", "<");
  Submap.put (")", ">");
  Submap.put ("#", "=");
 Prioritymap.put ("#", SubMap); }
}

Program test:

String exp = "4 * (Ten + 2) + 1 #";
EvaluateExpression ee = new evaluateexpression ();
OUT.PRINTLN (Ee.calcualte (exp));

The run result is 49.

I hope this article will help you with the C + + program design.

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.