| Author |
exception related
|
trish mo
Greenhorn
Joined: Feb 24, 2011
Posts: 14
|
|
Hi !
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 ?
Thanks
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3791
|
|
Hi. Welcome to JavaRanch!
You've got a couple of different problems there.
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.
|
 |
Joanne Neal
Rancher
Joined: Aug 05, 2005
Posts: 3011
|
|
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.
|
Joanne
|
 |
Wouter Oet
Saloon Keeper
Joined: Oct 25, 2008
Posts: 2700
|
|
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.
|
 |
trish mo
Greenhorn
Joined: Feb 24, 2011
Posts: 14
|
|
Matthew Brown wrote:Hi. Welcome to JavaRanch!
You've got a couple of different problems there.
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.
Yup, got it
This is the modified code :
Thanks a lot !
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3791
|
|
|
Yes, but....now try running that with a size of 6. You'll find it's not quite working right.
|
 |
 |
|
|
subject: exception related
|
|
|