jQuery in Action, 2nd edition*
The moose likes Beginning Java and the fly likes 2-Dimensional Arrays? Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "2-Dimensional Arrays?" Watch "2-Dimensional Arrays?" New topic
Author

2-Dimensional Arrays?

Ashley Kin
Ranch Hand

Joined: Oct 18, 2011
Posts: 36
Hi, I'm trying to make a 2-dimensional array of integers called grid with 4 rows and 6 columns.
I'm supposed to write a loop that initializes the second row to store integers starting with 2 and incrementing by 3 for each element in the row.
So the second row would have integers 2, 5, 8, 11, 14, 17.

This is what I have so far:
I'm not sure how to increment by 3 each time.
And am I referring to the right location in the array by saying grid[1][1]? Is that row 2, column1?
Thanks for any help!




also, I'd also appreciate help with ArrayIndexOutOfBoundsException. I think I'm going past the bounds of my array, but how can I avoid that when using a for loop?
Clivant Yeo
Ranch Hand

Joined: May 22, 2004
Posts: 124
Hi,

I'm supposed to write a loop that initializes the second row to store integers starting with 2 and incrementing by 3 for each element in the row.
So the second row would have integers 2, 5, 8, 11, 14, 17.




grid[1][1] refers to row 2, column 2, not row 2, column 1.



should be



The inner loop should be j++ instead of i++.


Clivant Yeo
My Personal Website
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 37940
    
  22
Not convinced, I am afraid. You should be iterating an array using its length field. An in Java™ there is no such thing as a two-dimensional array. Only arrays of arrays. You can traverse the outer array like thisAnd you can iterate its members like thisIf you write your for loops to iterate arrays like that, you will always be in the bounds of the array. Using i - 1 or i + 1 however, might take you out of the bounds of the array. i - 1 or i + 1 is sometimes unavoidable, but here you can have a count local variableAnd for completeness’ sake, this is how you can traverse an array backwardsHave you not been taught those forms of for-loop?
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
 
subject: 2-Dimensional Arrays?
 
Similar Threads
summing each row in a 2-dimensional array
2D array battleship
Arrays of Arrays
Array going out of bounds?
Problem with declaring dimensions of a general array? (edited)