Search code examples
javaexpressionexpression-evaluation

Evaluate expression for specific requirement in java


I have Expression object which has the following:

  1. Operator
  2. parameter
  3. value

Each simple Expression mentioned can be combined into a compound expression.

public SimpleExpresssion createcompound(SimpleExpression simple1,SimpleExpression simple2)    
    {
        CompoundExpression ce = new CompoundExpression();
        ce.lhs(simple1);
        ce.rhs(simple2);
        ce.operator(AND);    
    }

A complex example would look like ((1AND2)OR(3OR4)) where 1,2,3,4 are Expression objects. I am looking for a logic to evaluate the expression based on the parenthesis preference in the expression. Note: CompoundExpression is a extended class of Expression so the final output is a Expression object. Is it solvable easily? If not what are my options


Solution

    1. Convert the Expression to equivalent postfix expression.
    2. Evaluate the postfix expression using a stack.