# Thread: Explanation of Nested Loop (very strange)

1. Member
Join Date
Nov 2009
Posts
4
Rep Power
0

## [SOLVED] Explanation of Nested Loop (very strange)

Hey, I've been programming for a long time, but I'm new to java (I know it's still very similar to others). I'm having a strange result from a board(like chess) I'm making:

Here is the variable init.
Java Code:
```    //Board Dimensions
public static final int WIDTH = 20;
public static final int HEIGHT = 10;

//I'm using boolean because it's either a dot or an asterisk...
public static boolean[][] board = new boolean[WIDTH][HEIGHT];```

When I drew the board, the x and y flipped positions for some reason.
Originally I had this code:
Java Code:
```static void drawBoard()
{
for (int x = 0; x < WIDTH; x++)
{
for (int y = 0; y < HEIGHT; y++)
{
if (board[x][y] == true)
{
System.out.print( '*' );
}
else
{
System.out.print( '.' );
}
}
System.out.println();
}
}```
I was able to correct the problem by just reversing it like this:
Java Code:
```static void drawBoard()
{
//HAVE TO START WITH COLUMN AND INVERSE THE X Y
for (int x = 0; x < HEIGHT; x++)
{
for (int y = 0; y < WIDTH; y++)
{
if (board[y][x] == true) //NEED TO INVERT X AND Y TO MAKE WORK
{
System.out.print( '*' );
}
else
{
System.out.print( '.' );
}
}
System.out.println();
}
}```
And the desired output should be similar to "Conway's Game of Life" as this is supposed to be a replica.
Last edited by Jonotron; 11-25-2009 at 03:36 AM. Reason: Solved

2. Senior Member
Join Date
Nov 2009
Posts
235
Rep Power
5
Hello, in your first for loop, you print the heights and then make a new line, and then print the next column, I think what you want to do is print the entire width then make a newline, and then print the next widths. Like this:
Java Code:
``` static void drawBoard()
{
for (int y = 0; y < HEIGHT; y++)
{
for (int x = 0; x < WIDTH; x++)
{
if (board[x][y] == true)
{
System.out.print( '*' );
}
else
{
System.out.print( '.' );
}
}
System.out.println();
}
}```

3. Member
Join Date
Nov 2009
Posts
4
Rep Power
0
Oh wow, now that I think about it, that makes so much more sense. Thanks a lot!

4. Senior Member
Join Date
Nov 2009
Posts
235
Rep Power
5
Glad I could help.:)

5. Senior Member
Join Date
Mar 2009
Posts
552
Rep Power
6
I'm really starting to get annoyed by these ad posts... reported.

6. and deleted. Thanks.

#### Posting Permissions

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