使用Java的递归表达式求值程序 [英] Recursive expression evaluator using Java

查看:151
本文介绍了使用Java的递归表达式求值程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我打算写一个只进行加法和减法的表达式求值器。我有一个简单的算法来做到这一点;但是,我有一些实现问题。

I am going to write an expression evaluator which only does addition and subtraction. I have a simple algorithm to do that; but, I have some implementation problems.

我认为表达式为(它是一个字符串)

I considered an expression as (it is a String)

"(" <expression1> <operator> <expression2> ")"

这是我的算法

String evaluate( String expression )

   if expression is digit
      return expression

   else if expression is "(" <expression1> <operator> <expression2> ")"
      cut the brackets out of it
      expression1 = evaluate( <expression1> )
      operator = <operator>
      expression2 = evaluate( <expression2> )

   if operator is +
      expression1 + expression2

   else if operator is -
      expression1 - expression2 

我的问题是解析< expression1> < operator> < expression2> 。我怎样才能做到这一点?

My problem is parsing <expression1>, <operator> and <expression2> from the expression. How can I do that?

注意:我不是要求代码。我需要的只是一个想法。

Note: I'm not asking for a code. All I need is an idea to do that.

谢谢,

-Ali

推荐答案


我的问题是解析< expression1>,
< operator>和< expression2>来自
表达式

My problem is parsing <expression1>, <operator> and <expression2> from the expression

不要这样做,然后:)当你看到一个左括号时,你的递归调用表达。在表达结束时,要么你找到另一个操作符(所以你毕竟不在表达式的末尾),或者右括号,在这种情况下你从评价中返回。

Don't do that, then :) When you see an opening bracket, do your recursive call to expression. At the end of the expresssion, either you find another operator (and so you're not at the end of the expression after all), or a right-bracket, in which case you return from the evaluate.

这篇关于使用Java的递归表达式求值程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆