如何从 J2ME 中的字符串计算数学表达式
如何从 J2ME 中的字符串计算数学表达式。
例如,一个包含“2*4”的字符串。我想从该字符串计算数学表达式并得到结果为 8 (2*4)。我应该如何在 J2ME 中完成此操作。
在“Java™ Platform Standard Ed. 6”中,有一个名为“javax.script”的包用于计算字符串中的数学表达式。就像任何包或任何类都可用于 J2ME 来计算字符串中的数学表达式一样。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您需要处理嵌套表达式,只需编写自己的基于堆栈的解析器。
如果您不熟悉该算法,可以使用两个堆栈,一个用于保存运算符,另一个用于保存操作数。
对于基本情况,您将所有运算符和操作数解析到各自的堆栈中,然后通过弹出两个操作数和一个运算符进行评估,执行计算,然后将结果存储回操作数堆栈。继续下去,直到操作符栈为空并且操作数栈只有一个值(结果)。如果您用完运算符并且堆栈上有多个结果,则表达式中存在错误。
要处理括号(包括嵌套括号),请包含左括号和右括号的运算符。解析表达式时,如果遇到右括号,立即开始计算表达式(弹出两个操作数和一个运算符,将结果放回操作数堆栈),直到遇到左括号。然后继续解析表达式。
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.
以下是在 J2ME 中从字符串计算数学表达式的步骤
The following are the steps are used to evaluate the mathematical expression from the string in J2ME