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;
      }

I have been looking on the internet for some clues to this particular problem and it looks like there is some type of internal stack.

The internal stack that you mention must be the call stack. Every time a method is called a new element (called a stack frame) is pushed onto the call stack to hold all the local variables of the method and the place where execution will resume when the method returns.

Your popped value is never overwritten because it is a local variable and no method you call can ever touch it, even if you are recursively calling the method that contains popped. Each call gets its own version of popped in its own stack frame.

The call stack is designed to do what you expect. It gives every method call a clean slate and allows you to avoid worrying about how two method calls will interact in many cases. The only people whom I would expect to be surprised by that behaviour are the ones who are used to working in those few languages that don't have local variables such as some versions of Basic and Perl before version 5.

Edited 3 Years Ago by bguild

This question has already been answered. Start a new discussion instead.