Results 1 to 3 of 3
  1. #1
    MKM5955 is offline Member
    Join Date
    Jan 2015
    Location
    Canada
    Posts
    1
    Rep Power
    0

    Default Looping through 2D array

    I'm a beginner in java, and i just had a question on looping through 2d arrays.

    This code works when printing '*' to show the number of elements in a 2d array:

    static int [][] gameboard = new int[3][7];
    for (int i = 0; i < gameboard.length ; i++) {
    for (int j = 0; j < gameboard[0].length ; j++) {
    System.out.print("*");
    Thread.sleep(1000);

    but then this does not:

    static int [][] gameboard = new int[3][7];
    for (int i = 0; i < gameboard.length ; i++) {
    for (int j = 0; j < gameboard[i].length ; j++) {
    System.out.print("*");
    Thread.sleep(1000);

    The difference is on the third line where i did gameboard[i] instead of gameboard[0]. I get a runtime error on the second one. How come?

  2. #2
    pbrockway2 is offline Moderator
    Join Date
    Feb 2009
    Location
    New Zealand
    Posts
    4,716
    Rep Power
    18

    Default Re: Looping through 2D array

    I get a runtime error on the second one.
    What is the runtime exception? Post the whole thing.

    [Edit] It might pay to also copy and post the exact code you are using in the second case.
    Last edited by pbrockway2; 01-13-2015 at 01:30 AM.

  3. #3
    jim829 is offline Senior Member
    Join Date
    Jan 2013
    Location
    Northern Virginia, United States
    Posts
    6,226
    Rep Power
    14

    Default Re: Looping through 2D array

    Why don't you include the complete code. Should be pretty simple. Since didn't want to wait 21 seconds I took out the sleep. They both work fine for me.

    Regards,
    Jim
    The JavaTM Tutorials | SSCCE | Java Naming Conventions
    Poor planning on your part does not constitute an emergency on my part

Similar Threads

  1. Looping through an Array
    By IcedWings in forum Java Applets
    Replies: 1
    Last Post: 03-11-2013, 01:47 AM
  2. Need Help looping through an Array
    By grimlek in forum New To Java
    Replies: 20
    Last Post: 12-19-2012, 06:25 AM
  3. Looping through an array
    By Person264 in forum New To Java
    Replies: 0
    Last Post: 12-12-2012, 10:59 PM
  4. Looping over averages in an int[][] array
    By adventurerOK in forum Advanced Java
    Replies: 1
    Last Post: 09-28-2011, 09:16 PM
  5. Looping Array Elements
    By enzyme in forum New To Java
    Replies: 3
    Last Post: 11-26-2009, 04:35 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •