Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Why is my array printing twice?

I am trying to print a 2d array, and for some reason it keeps printing twice. I can't figure it out...

Here is the loop i'm using, and what it prints.

{

int[][]gameBoard = {{1,2,3},{4,5,6},{7,8,9}};

{

for(int k = 0; k<gameBoard.length; k++)

{

for(int j = 0; j<gameBoard.length; j++)

{

System.out.print("| " + gameBoard[k][j] + " |");

}

System.out.println();

}

}

| 1 || 2 || 3 |

| 4 || 5 || 6 |

| 7 || 8 || 9 |

| 1 || 2 || 3 |

| 4 || 5 || 6 |

| 7 || 8 || 9 |

2 Answers

Relevance
  • 10 years ago
    Favorite Answer

    Your code is correct. I ran the program and it printed out:

    | 1 || 2 || 3 |

    | 4 || 5 || 6 |

    | 7 || 8 || 9 |

    Maybe because you ran your program twice.

    The other answer is incorrect. There is no such thing as gameBoard[k].length

    Hope that helps.

    =D

  • 10 years ago

    It looks like you have a few extra brackets in your code, like after the "int[][]" line. Double check everything and make sure that what you need is exactly this. Also, you should use for the inner for-loop the length of the individual sub array like this:

    for(int j = 0; j<gameBoard[k].length; j++)

Still have questions? Get your answers by asking now.