0

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!

Simba18
  • 13
  • 1
  • For the parentheses part, look [here](http://stackoverflow.com/questions/26974739/split-a-complex-string-based-on-grouping-of-small-brackets-in-java/26975501#26975501). As parentheses appear nested in pairs, simple indexOf will not easily be done. In that answer nested expressions are resolved first. – Joop Eggen Nov 27 '14 at 15:34

2 Answers2

1

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

Community
  • 1
  • 1
Xavi López
  • 27,550
  • 11
  • 97
  • 161
  • Thank you so much I am an idiot. Yes there are other ways this was my assignment though. Thanks again – Simba18 Nov 27 '14 at 15:47
0

It looks like you are new to languages and compilers. If you want to build a Rock Solid expression evaluator please search for "recursive descent parser" implementation in Java. Even better: build a table driven parser (eg based on JavaCC) but the learning curvevis steeper.

robert
  • 1,921
  • 2
  • 17
  • 27