在新方法中替换二维数组的值

时间:2013-11-13 00:05:53

标签: java arrays random replace char

所以我必须为我的任务的一部分创建一个名为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();
    }

}

2 个答案:

答案 0 :(得分: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]);
      }
   }
}

答案 1 :(得分:0)

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