• Post Reply Bookmark Topic Watch Topic
  • New Topic

outofboundsexception  RSS feed

 
Josh Galeigh
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know it is the length of the array but I can't seem to figure out what the source of the problem is.



Array: new int[][] { { 0, 1, 2, 3 }, { 10, 11, 12, 13 },
{ 20, 21, 22, 23 } };

java.lang.ArrayIndexOutOfBoundsException: 3
on this line of course:tgt[tgtX][tgtY]=source[srcX][srcY];

It doesn't seem to matter what I do to the array sizes I can't fix it. Thanks for any help!
 
Tushar Goel
Ranch Hand
Posts: 934
4
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

Looks like there is a problem with the loop.

What value of srcX and srcY you got when tgtX = 3 ???
 
Chris Barrett
Bartender
Posts: 321
24
Eclipse IDE Firefox Browser
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Josh,

srcW is equal to 3 as it is the outer array element length
srcH is equal to 4 as it is the inner array element length

In the loop, you flipping the outer and inner element length counts:


If you insert a System.out.println(srcY); just after you assign it a value in your loop, you will see on the fourth iteration srcY == -1.

Cheers!
Chris
 
Josh Galeigh
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I got it, thanks. First time working with 2D. Gets confusing pretty fast.
 
Chris Barrett
Bartender
Posts: 321
24
Eclipse IDE Firefox Browser
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Josh,

Great to hear you got it!

For 2D arrays, think of them as rows and columns. The first element count is the number of rows and the second element count is the number of columns. You start on the first row, iterate across the columns and then move down to the next row.

Now, when you get to 3D arrays... ugggg... ;)

Cheers!
Chris
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There's no such thing as a 2D array in Java. That is an array of arrays.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!