Search code examples
javaexpressionparentheses

Check if an operator is nested inside parenthesis


I am trying to build a calculator that will evaluate expressions read from a string in java.

My algorithm recursively splits the input string by its lowest precedence operation (i.e. right-most +) and then evaluates when it is left with a binary operation.

For some reason I am having trouble checking whether or not an operator is nested within parenthesis.

This is my check - exp is the string of the expression, lastMD is the index at which the operator in question is in exp

if (exp.lastIndexOf('(', lastMD) != -1 && exp.lastIndexOf('(', lastMD) < lastMD && exp.lastIndexOf('(', lastMD) > exp.lastIndexOf('(', lastMD)) {
    // it is in parenthesis
}
else { 
    // it is not in parenthesis
}

For some reason it is not working and jumping to the else even when lastMD is contained by parenthesis.

What am I missing?

Thanks!


Solution

  • The condition as it is expressed now can never return true:

    int i = exp.lastIndexOf('(', lastMD);
    if (i != -1 && i < lastMD && i > i) { ...
    

    i > i will always evaluate to false.

    As a side note, as already pointed out in the comments, you might consider using another approach such as a simple parser to build a traversable AST (look into ANTLR).

    The following related question might be also useful: How does a simple calculator with parentheses work?.