开发者

How to evaluate the mathematical expression from the string in J2ME

How to evaluate the mathematical expression from the string in J2ME.

For example a string containing "2*4".From the str开发者_Python百科ing i want evaluate the mathematical expression and get the result as 8 (2*4).How should i done this in J2ME.

In "Java™ Platform Standard Ed. 6 " there is a package namely "javax.script" is used for evaluating mathematical expressions from string.Like that any package or any class is available for J2ME to evaluate the mathematical expression from the string.


If you need to handle nested expressions just write your own stack based parser.

If you're not familiar with the algorithm, you use two stacks, one for holding operators and the other for holding operands.

For the basic case you parse all the operators and operands into their respective stacks then evaluate by popping off two operands and an operator, performing the calculation then storing the result back on the operand stack. Continue until the operator stack is empty and the operand stack has only one value (the result). If you run out of operators and there is more than one result on your stack then there is an error in the expression.

To handle parentheses (including nested parentheses) you include operators for the left and right parens. When parsing the expression if you encounter a right paren start evaluating the expression immediately (popping two operands and an operator, placing the result back on the operand stack) until you encounter a left paren. Then resume parsing the expression.


The following are the steps are used to evaluate the mathematical expression from the string in J2ME

  1. Read the expression in a string variable.Here the expression is in infix form.
  2. Convert the expression in the string variable into a postfix form and store it in a another string variable namely "postfix_str".
  3. Evaluate the expression in the postfix form (The value in the "postfix_str" data) using the Stack.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜