Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
    Bookmark Topic Watch Topic
  • New Topic

Array going out of bounds?

 
Ashley Kin
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Report post to moderator
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
Rancher
Posts: 1776
  • Likes 1
  • Mark post as helpful
  • send pies
  • Report post to moderator
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
Posts: 36
  • Mark post as helpful
  • send pies
  • Report post to moderator
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
Rancher
Posts: 1776
  • Mark post as helpful
  • send pies
  • Report post to moderator
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
Pie
Posts: 48972
60
  • Mark post as helpful
  • send pies
  • Report post to moderator
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
Pie
Posts: 48972
60
  • Mark post as helpful
  • send pies
  • Report post to moderator
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.
 
    Bookmark Topic Watch Topic
  • New Topic