Results 1 to 7 of 7
- 03-02-2010, 04:16 PM #1
Member
- Join Date
- Mar 2010
- Posts
- 10
- Rep Power
- 0
How to handle ArrayIndexOutOfBoundsException
Hi all,
I am trying to find a way to handle an ArrayIndexOutOfBoundsException.
this will give an exception. Is there a way (maybe try-catch) to set the variable to the previous code to 0 i.e every time an index is out of bound to set it to 0?Java Code:int [] plegma = new int[10]; int x = plegma[11]);
Thank you for your help.
-
- 03-03-2010, 07:57 AM #3
Member
- Join Date
- Mar 2010
- Posts
- 10
- Rep Power
- 0
Thanks for your help Fubarable!
- 03-03-2010, 02:55 PM #4
- 03-03-2010, 03:07 PM #5
Member
- Join Date
- Mar 2010
- Posts
- 10
- Rep Power
- 0
Thank you j2me64. Actually I got a 2d matrix where the state of each element depends on the state of its neighbors . The elements on the borders have no neighbors from the one side.
I wanted to know what is the best practice (acquire good programming habits :)) in this case, to handle the exception or add an additional row, column on this side it and set the its state to 0.
-
I wouldn't use exception here or an extra row or column but rather use simple math to know when I'm at the boundaries and to not go beyond. Math.min and Math.max can be helpful. For instance look at post #16 here: MineSweeper!
- 03-03-2010, 03:16 PM #7
- Join Date
- Sep 2008
- Location
- Voorschoten, the Netherlands
- Posts
- 11,405
- Blog Entries
- 7
- Rep Power
- 17
Try both alternatives: one version where you check whether or not your in a corner or on an edge and another where you've added two rows and two columns around the actual values of the matrix; note that you have to adjust your loop bounds to:
... and see which version you like most (I like the additional rows/columns trick most because there is no bounds checking needed).Java Code:for (int i= 1; i < array.length-1; i++) ...
kind regards,
Jos
Similar Threads
-
ArrayIndexOutOfBoundsException
By Corey in forum New To JavaReplies: 5Last Post: 02-02-2010, 01:25 AM -
ArrayIndexOutOfBoundsException
By flaskvacuum in forum New To JavaReplies: 6Last Post: 07-14-2009, 05:36 PM -
[SOLVED] ArrayIndexOutOfBoundsException
By thelinuxguy in forum Advanced JavaReplies: 1Last Post: 05-07-2009, 10:34 PM -
ArrayIndexOutofBoundsException help
By filly444 in forum New To JavaReplies: 9Last Post: 09-03-2008, 05:16 PM -
ArrayIndexOutOfBoundsException
By daredavil82 in forum New To JavaReplies: 2Last Post: 12-14-2007, 09:29 PM


LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks