Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

exception related

 
trish mo
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3742
16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

 
Wouter Oet
Saloon Keeper
Posts: 2700
IntelliJ IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Why do you use Exceptions and not a simple if-statement? e.g.:
 
trish mo
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, but....now try running that with a size of 6. You'll find it's not quite working right.
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic