【发布时间】:2012-03-01 08:16:23
【问题描述】:
我正在学习 Java 并从事基于网格的 guessingGame 项目,但我的 loadtargetGrid() 方法遇到了一些困难。
我有一个名为 Grid 的二维字符串数组,我想在六个随机选择的网格位置放置六个符号“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;
}
}
这就是我目前所拥有的。我尝试使用带计数器的 while 循环在 6 个随机位置放置“X”。它可以编译,但我不确定这是否有效,我不知道如何检查我的代码是否正确。
【问题讨论】:
-
您不想从 ROWS 和 COLUMNS 中减去 1。 nextInt 方法已经将结果限制为 0 到 ROWS-1 或 0 到 COLUMNS-1。您收到的任何一个答案都可以让您避免重复的位置。
-
没错!我以为 nextInt(int n) 方法会从 0 到 n 值,但 n 值是排他性的。谢谢