Reputation: 13
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!
Upvotes: 0
Views: 194
Reputation: 27880
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?.
Upvotes: 1
Reputation: 2027
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.
Upvotes: 0