John - 3 months ago 8
Java Question

# For Loop 2D Array

in this program, i want to replace three 'N's at random location with three 'O's. i've tried to use a forloop to achieve that however, the amount of 'O' that i get is inconsistent. i'm not exactly sure which part went wrong... help please!

``````static char grid[][];
public static void Board()
{
Random rn = new Random();
grid = new char [3][3];
for(int row = 0; row<grid.length; row++)
{
for(int col = 0; col<grid.length; col++)
{
grid[row][col] = 'N';
for(int i = 0; i<3; i++)
{
grid[rn.nextInt(3)][rn.nextInt(3)] = 'O';
}
System.out.print(grid[row][col]);
}
System.out.println();
}
}
``````

Answer

You need to separate your loops.

First initialize the array with `N`s, and then replace 3 `N`s :

``````for(int row = 0; row<grid.length; row++) {
for(int col = 0; col<grid[row].length; col++) {
grid[row][col] = 'N';
}
}
for(int i = 0; i<3; i++) {
grid[rn.nextInt(3)][rn.nextInt(3)] = 'O';
}
``````

Running the `for(int i = 0; i<3; i++)` inside the inner initialization loop causes 3 random cells to be assigned `O` 3x3 times, and these cells can later be overwritten with `N`, since you are doing it before the initialization is done.

You should also note that the cells assigned by `grid[rn.nextInt(3)][rn.nextInt(3)] = 'O'` may not be 3 unique cells, so you might still end up with less than 3 `O`s.

You can replace the second loop with a while loop to ensure that exactly 3 cells are replaced :

``````int i = 0;
while(i < 3) {
int x = rn.nextInt(3);
int y = rn.nextInt(3);
if (grid[x][y] != 'O') {
grid[x][y] = 'O';
i++;
}
}
``````
Source (Stackoverflow)
Comments