Meaningless Drivel is fun!*
The moose likes Beginning Java and the fly likes Array going out of bounds? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply locked New topic
Author

Array going out of bounds?

Ashley Kin
Ranch Hand

Joined: Oct 18, 2011
Posts: 36
I'm trying to print an array in the form of a 4 by 6 grid.
My for loop is getting the error: ArrayIndexOutOfBoundsException: 4
What does this mean and how do I go about fixing it?
Thanks!

John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
Issue is in the grid[i].length. The array size you have given is only [4][6] and hence you can check only till grid[3].length.

I believe the code you intend to have is grid[1].length?
Ashley Kin
Ranch Hand

Joined: Oct 18, 2011
Posts: 36
When I replace i with 1, this is the output I get:

[[I@635b9e68, [I@13fcf0ce, [I@43256ea2, [I@4e82701e]

I'm not sure if this is an error or what?
John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
That's not an error. Arrays class has overridden the toString() method to print that way. It's just an object representation and not the array contents. You could read these http://docs.oracle.com/javase/6/docs/api/java/util/Arrays.html#toString(java.lang.Object[]) and Object:toString() to know what the printed strings represent.

However I think you have to iterate again the grid[1] using a for loop to print its contents.

Few questions -
1. Why have you ignored starting to store elements from grid[0]?
2. Why you leave rest of the grid array as empty? (note grid[0], grid[2], grid[3] all are unused).
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38765
    
  23
John Jai wrote:That's not an error. Arrays class has overridden the toString() method to print that way. . . .
Has it? I am not convinced about your answer. What you are seeing is the output of an un-overridden toString() method. You will find that the only overridden member of an array type is clone().
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38765
    
  23
I gave you an answer yesterday, which would have avoided any risk of going outwith the bounds of your arrays (you have 5 arrays, not one 2D array). I also suggested how you can avoid using i + 1 and i - 1.

I think this is a duplicate discussion, so I shall close it and ask everybody to continue on that thread I linked to on the first line of this post.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Array going out of bounds?