I wrote my own little program on stack which goes like this :
Why does the pop function work incorrectly...looks like the code never enters the try block but that's not possible !
Can anyone provide some answers ?
1. You create a stack of size 5, and then try and add 6 items. That's fine, the error capture handles that...except the error capture does not reset the top pointer. So now any attempt to pop causes an ArrayIndexOutOfBoundsException, as the pointer is already set to an invalid value.
2. Fix that, and you'll see the second problem. You're calling pop twice on each iteration. Once to check the value is OK, but then you pop it again. So you count down in twos. I doubt that's what's intended.
It would help if you told us what is actually happening, but I suspect the following.
This pushes 6 elements on to the stack, but you have only set the stack size to 5, so I presume you are getting a stack overflow.
You then try to pop an element off the stack, but top will still be out of bounds so you will get a stack underflow.
Why do you use Exceptions and not a simple if-statement? e.g.:
"Any fool can write code that a computer can understand. Good programmers write code that humans can understand." --- Martin Fowler
Please correct my English.
1. You create a stack of size 5, and then try and add 6 items. That's fine, the error capture handles that...except the error capture does not reset the top pointer. So now any attempt to pop causes an ArrayIndexOutOfBoundsException, as the pointer is already set to an invalid value.
2. Fix that, and you'll see the second problem. You're calling pop twice on each iteration. Once to check the value is OK, but then you pop it again. So you count down in twos. I doubt that's what's intended.