I'm trying to evaluate a string from left to right as an Integer with numbers between 0-9 and the four basic operators (like "5+8+(8/4)"
should evaluate as 15
or "9+((3+4)*5)"
as 44
or "4+2*6"
as 36 since 4+2 is calculated first due to all operators having same precedence), but I'm having trouble implementing parentheses.
I've managed to get it working if I don't include parentheses. I do this by parsing through the string using a StringTokenizer in a while loop. Each token is stored in a variable, and if it contains a number it's added to a Stack, and if it contains an operator it's added to a Stack. Then, when there are two numbers in the Integer stack, I evaluate them based on the operator in the operator stack. It just goes through like this for the whole string until str.hasMoreTokens()
is true, and the while loop breaks. So, something like 8-5+7*3+1/2-4
works perfectly, but I can't find a way to make parentheses work with any expressions
I've tried using String newStr = str.replaceFirst("[^(]*(", "");
to try to cut off everything and including the first (
then recursively evaluate what's left and so on, but I think this is way more complicated than it had to be and I couldn't get it working regardless. I've been thinking for hours, but I can't come up with a simpler way.
Thanks, I'm completely lost at this point, so any guidance/suggestions would be great.