• Post Reply Bookmark Topic Watch Topic
  • New Topic

Array Out Of Bounds  RSS feed

 
Derek Smiths
Ranch Hand
Posts: 119
Eclipse IDE Mac VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've setup an array that I would like to analyze by adding up the contents of each column, however, the out of bounds exception pops up when I try to execute the program. I know the book usually expresses this operation the other way around, where the row is the argument of the first for statement, but I've set my array up where I need to add each row before moving to the next column. vowelCounter is a 5x3 array.
 
Stefan Evans
Bartender
Posts: 1837
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does it display an error message?
Does it tell you which index you tried to access?

I would suggest putting a debugging message in your program



See what that tells you about what index you are trying to get, and what it should be.
 
Derek Smiths
Ranch Hand
Posts: 119
Eclipse IDE Mac VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you. I tried that and saw that the array was trying to go to column 3 which does not exist. Shouldn't the for statement be preventing the out of bounds? Also, I saw that my initial for loop to define max was wrong. I've since changed it, but the value returning is still inaccurate.


Update

I just figured out, by chance, why my array was going out of bounds, but I still don't understand why vowelCounter[0] is used:

 
Stefan Evans
Bartender
Posts: 1837
10
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You said that you had a 5 x 3 array - vowelCounter[5][3]
Essentially that is an array of arrays.

vowelCounter is an array of 5 elements (0 - 4)
vowelCounter[0] is an array of 3 elements (0 - 2).
vowelCounter[1] is an array of 3 elements (0 - 2).
vowelCounter[2] is...

But the array does not necessarily have to be 'square'
vowelCounter[2] COULD potentially be an array with 7 elements in it, so the correct way to loop through it should probably be:



I've just reversed the row/column loops, and had the column one use 'row' rather than '0'.
The code was actually working - given the assumption that you had a 'square' array

I hope that explains why the column limit is what it was.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!