Hello,
Would someone be willing to take a look at this segment of code?
I am trying to figure out how this segment of code operates. I can see how the program can evaluate a simple prefix statement like + 7 6. I cannot see how the program can solve a statement like + + 7 6 + 5 4. I've inserted some print statements in order to see what the program is doing and it is showing
a = 7, b = 6, a = 13, a = 5, b = 4, b = 9, (22 = total). I cannot see
how a = 13, where is the first + symbol is stored, how b = 9. It seems like these three should be erased after being popped and then covered up by another 'popped = stack.pop();' statement. Where are these being stored?
Thank you,
Hank
/**
evaluate Prefix Stack, return int
*/
public static int evaluate(Stack<String> stack)
{
String popped = stack.pop();
if(!(popped.compareTo("+") == 0 || popped.compareTo("*")== 0))
{
int x = Integer.parseInt(popped);
return x;
}
else if(popped.compareTo("+") == 0)
{
int a = evaluate(stack);
System.out.println("a" + a);
int b = evaluate(stack);
System.out.println("b" + b);
return a + b;
}
else
return 0;
}