Using Java’s recursive expression evaluator
•
Java
I want to write an expression evaluator that only does addition and subtraction I have a simple algorithm to do this; However, I have some implementation problems
I think an expression (it's a string) @ h_ 301_ 3@
"(" <expression1> <operator> <expression2> ")"
This is my algorithm @ H_ 301_ 3@
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
My problem is to parse < expression1 > < operator > and < expression2 > from expression How can I do this@ H_ 301_ 3@
Note: I'm not asking for a code All I need is an idea@ H_ 301_ 3@
Thank you, @ h_ 301_ 3@
- Ali@H_301_3 @
Solution
Don't do this, then:) when you see an opening bracket, your recursive call expression At the end of the expression, either find another operator (so you're not at the end of the expression at all) or a closing parenthesis, in which case you'll return from the evaluation@ H_ 301_ 3@
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码