如何将字符串放在2D数组中随机选择的位置

Pou*_*pen 5 java arrays random

我正在学习Java并在基于网格的thinkssingGame项目上工作,我的loadtargetGrid()方法遇到了一些困难.

我有一个名为Grid的字符串的2D数组,以及我想在六个随机选择的网格位置放置六个符号"X".我想对其他位置什么都不做,默认情况下保留null.

    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;
      }
}
Run Code Online (Sandbox Code Playgroud)

这就是我到目前为止所拥有的.我尝试使用带有计数器的while循环将"X"放在6个随机位置.它编译但我不确定这是否有效,我不知道如何检查我的代码是否正确.

Dan*_*n W 3

您可能无法将所有 6 个目标都放在网格上,因为您可能会两次获得同一个位置。尝试这个:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)