I'm learning Java and working on a guessingGame project based on a grid and I'm having some difficulties for my loadtargetGrid() method.
I have a 2D array of String named Grid, and what I want to place six symbols "X" in six randomly-chosen grid locations. I want to do nothing with the others location and leave them with null by default.
public class Grid
{
public static final int ROWS = 5; // number of rows
public static final int COLUMNS = 5; // number of columns
public static final int NUMBER_OF_TARGETS = 6; // number of targets in the grid
private String[][] grid; // the grid itself, a 2-D array of String
private Random random; // random number generator
//Constructor
public Grid()
{
grid = new String[ROWS][COLUMNS];
random = new Random();
}
//method
public void loadTargetGrid()
{
int counter = 0;
while(counter < NUMBER_OF_TARGETS){
int randRow = random.nextInt(ROWS - 1);
int randColumn = random.nextInt(COLUMNS - 1);
grid[randRow][randColumn] = "X";
++ counter;
}
}
That's what I have so far. I tried to use a while loop with a counter to place a "X" at 6 random positions. It compiles but I'm not sure if this works and I don't know how to check if my code is correct.
You could potentially not have all 6 targets on the grid because you could get the same spot twice. Try this:
int counter = 0;
while(counter < NUMBER_OF_TARGETS){
int randRow = random.nextInt(ROWS - 1);
int randColumn = random.nextInt(COLUMNS - 1);
if (grid[randRow][randColumn] == null) {
grid[randRow][randColumn] = "X";
++ counter;
}
}
If you get the same randomly chosen coordinates more than once, you won't end up with NUMBER_OF_TARGETS distinct locations. You might try something like
int randRow, randColumn;
do {
randRow = random.nextInt(ROWS);
randColumn = random.nextInt(COLUMNS);
} while (grid[randRow][randColumn] != null);
grid[randRow][randColumn] = "X";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With