• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

2-Dimensional Arrays?

 
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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?
 
Ranch Hand
Posts: 124
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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++.

 
Marshal
Posts: 79406
377
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
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.
reply
    Bookmark Topic Watch Topic
  • New Topic