0

所以我必须为我的一部分作业创建一个名为 populateRandom 的方法。我目前有一个打印 8 x 8 板的网格,并且每个“单元格”目前都包含一个“$”。这都是通过我创建的 drawGrid 方法打印的。对于这个随机填充,我必须用我的一个字符数组中的随机字符填充网格。我目前拥有它,因此它会打印一个完整的单独网格,而不是替换当前的网格。我将如何覆盖已经存在的值......这是我的代码......到目前为止,它只打印选项数组中的一个值,我希望我的网格填充多个不同的值(& $*+ 等)。谢谢!希望这已经足够清楚了。PS:忽略注释掉的东西。'

public static void main(String[] args) 
{
    System.out.println("How to play: type a row and column index, followed by \n" +
                        "the direction to move it: u (up), r (right), d (down), l (left)");     
    char[][] grid = new char[8][8];
    char[] options = {'*','$','@','+','!','&'};
    drawGrid(grid);
    populateRandom(grid,options);
    System.out.println("Enter <row> <column> <direction to move> or q to quit");
    //char randomChar = 66;
    //System.out.println(randomChar);
}

   public static void drawGrid(char[][] grid)
   {
        System.out.println("\t1 \t2 \t3 \t4 \t5 \t6 \t7 \t8");
        System.out.println();
        //Random r = new Random();

        for(int row=0 ; row < grid.length ; row++ )
        {
            System.out.print((row+1)+"");
            for(int column=0 ; column < grid[row].length ; column++)
            {
                System.out.print("\t"+ "$");

            }
                System.out.println();
        }
            System.out.println();
    }

   public static void populateRandom(char[][] grid, char[] options) 
   {

       Random randomGenerator = new Random();
       int randomIndex = randomGenerator.nextInt(5); 

       for(int row=0 ; row < grid.length ; row++ )
        {
           // System.out.print((row+1)+"");
            for(int column=0 ; column < grid[row].length ; column++)
            {
                System.out.print("\t"+ options[randomIndex]);

            }
                System.out.println();
        }
            System.out.println();
    }

}

'

4

2 回答 2

0

您只需要将网格数组设置为随机生成器生成的随机值在字符数组中的索引。

public static void populateRandom() {
Random randomGenerator = new Random();
for(int row = 0; row < grid.length; row++) {
      for(int column=0; column < grid[row].length; column++) {
         int randomIndex = randomGenerator.nextInt(5); 
         grid[row][column] = options[randomIndex]);
      }
   }
}
于 2013-11-13T00:12:25.920 回答
0

打印时没有使用二维数组中的值。您只需使用它的索引。您应该将值分配到二维数组中,然后在打印网格时使用它们。

于 2013-11-13T00:12:30.860 回答