I got a school-project where I was given this information:
for i=1 to m
if c_i is an operand: Transfer c_i to output.
if c_i is a left parentheses: Push c_i to tmp.
if c_i is a right parentheses: Pop elements from tmp and transfer
them to output until a left-parentheses
is met. Pop left-parentheses.
if c_i is an operator: Let the top tmp element be t. Pop and
transfer elements from tmp to output
until:
p(t) < p(c_i) or
t is a left-parentheses or
tmp is empty.
Push c_i to tmp.
Transfer the remaining elements in tmp to output.
I have been doing exactly these steps, but my output only gets right som times. I guess that Im thinking wrong somewhere around the if statement with the operators. I've constantly been debugging for 2 days now, and I just cant find the solution.
I would be very pleased if someone would like to check my code. The operatorCheck function is made for solving this: "We use the subroutine p to specify the priorities of the operators:
p(+) = 0,
p(−) = 0, p(∗) = 1, p(/) = 1
. This means that addition and subtraction have lower priority compared to multiplication and division."
Code: http://pastebin.com/TA7UGiGc
Thank you!
You're looping and removing the first letter from tmp
without getting the next letter to compare with in the while loop, therefore you need to get a new character inside the while loop.
The substring is also removing the wrong characters from tmp
, it should keep everything except the first letter and that's accomplished with tmp.substring(1, tmp.length())
I have fixed that block of code below:
else if (character == '+' || character == '-' || character == '*' || character == '/'){
while (true) {
char t = tmp.length() > 0 ? tmp.charAt(0): ' ';
if (operatorCheck(t) < operatorCheck(character) || t == '(' || tmp.length() < 0) {
break;
}
output += t;
tmp = tmp.substring(1, tmp.length());
}
tmp = character + tmp;
}