如何从 J2ME 中的字符串计算数学表达式

发布于 2024-10-03 07:58:20 字数 217 浏览 1 评论 0原文

如何从 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

丶视觉 2024-10-10 07:58:20

如果您需要处理嵌套表达式,只需编写自己的基于堆栈的解析器。

如果您不熟悉该算法,可以使用两个堆栈,一个用于保存运算符,另一个用于保存操作数。

对于基本情况,您将所有运算符和操作数解析到各自的堆栈中,然后通过弹出两个操作数和一个运算符进行评估,执行计算,然后将结果存储回操作数堆栈。继续下去,直到操作符栈为空并且操作数栈只有一个值(结果)。如果您用完运算符并且堆栈上有多个结果,则表达式中存在错误。

要处理括号(包括嵌套括号),请包含左括号和右括号的运算符。解析表达式时,如果遇到右括号,立即开始计算表达式(弹出两个操作数和一个运算符,将结果放回操作数堆栈),直到遇到左括号。然后继续解析表达式。

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.

花辞树 2024-10-10 07:58:20

以下是在 J2ME 中从字符串计算数学表达式的步骤

  1. 读取字符串变量中的表达式。这里的表达式采用中缀形式。
  2. 将字符串变量中的表达式转换为后缀形式并将其存储在另一个字符串变量“postfix_str”中。
  3. 使用堆栈计算后缀形式的表达式(“postfix_str”数据中的值)。

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.
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文