Question

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

For example a string containing "2*4".From the string 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.

Was it helpful?

Solution 2

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.

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top