Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive expression evaluator using 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> ")"

Here is my algorithm

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 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.

Thank you,

-Ali

like image 233
629 Avatar asked Nov 01 '10 21:11

629


People also ask

What is evaluator in Java?

gnu.jel.Evaluator. public class Evaluator extends java.lang.Object. This is the main frontend to JEL. It is intended for compilation of algebraic expressions involving functions. Syntax allows variables, which can be either a public fields of certain objects or functions with no arguments.

What is recursive call in Java with example?

In Java, a method that calls itself is known as a recursive method. And, this process is known as recursion. A physical world example would be to place two parallel mirrors facing each other. Any object in between them would be reflected recursively.


1 Answers

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.

like image 61
The Archetypal Paul Avatar answered Oct 10 '22 06:10

The Archetypal Paul