programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering OS Languages Paradigms IDEs Build Tools Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

outofboundsexception

Josh Galeigh
Ranch Hand
Posts: 49
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
• 1

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
• 1
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
I got it, thanks. First time working with 2D. Gets confusing pretty fast.

Chris Barrett
Bartender
Posts: 321
24
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
• 1
There's no such thing as a 2D array in Java. That is an array of arrays.