用户指定的二维数组元素值

User specified 2d array element values

        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                while (treasures >= 0) {
                    mapArray[i][j] = rnd.nextInt(2);
                    treasures -= 1;
                }
            }
        }

用户指定数组的高度和宽度,以及此数组包含的数量 "treasures"。代码应循环遍历数组的所有元素,为它们赋予 0 或 1 的值(直到用户输入的宝藏数量达到 0 )。

宝物指示为1.

目前 for 循环仅针对第一个 ( [0] [0] ) 元素。

您应该消除 while 循环,因为它会阻止 ij 递增直到它结束,这就是为什么只分配 mapArray[0][0] 的原因。

    for (int i = 0; i < height && treasures >= 0; i++) {
        for (int j = 0; j < width && treasures >= 0; j++) {
            mapArray[i][j] = rnd.nextInt(2);
            treasures -= 1;            
        }
    }

请注意,如果treasures < height * width,数组的某些元素将默认包含0。

删除 while 循环,因为它只对 mapArray[0][0] 强制执行 运行 并且 while 循环在宝藏变为零时结束。这最终终止了所有循环。

我认为 "treasures" 的数量与“1”有关。因此,如果用户希望数组的高度为 4,宽度也为 4,并且 "treasures" 为例如 3,我会期望这样的结果:三个“1”和其余的“0”

     0110
     1000
     0000
     0000

如果那样的话你可以试试

Random rnd = new Random();
    int [][] grid = new int[height][width];
    int treasures = 3;

        for (int[] row : grid){                
            for (int n : row){                    
                if(treasures>0){
                    n = rnd.nextInt(2);
                    if(n==1){
                       treasures -= 1;
                    }
                }
                System.out.print(n);
            }
          System.out.println();
        }

为了理解您的代码,我鼓励您拿起笔写下您的代码的作用。

例如:

  • 输入高度=2,宽度=3,宝物=1
  • 步骤 1 i=0 和高度>i => 2>1 => 继续(高度=2,宽度=3 , 宝物=1, i=0)
  • 步骤 2 j=0 和宽度>j => 3>0 => 继续(高度=2,宽度=3 , 宝物=1, i=0, j=0)
  • 第三步宝藏>=0=>1>=0=>继续
  • 步骤 4 mapArray[i][j] = rnd.nextInt(2); => mapArray[0][0] = rnd.nextInt(2);
  • 步骤5 宝物-= 1 => 宝物= 0 (高=2,宽=3,宝物=0,i =0, j=0)
  • 步骤 6 宝藏 >= 0 => 0>=0 => 继续 [我想你不想要这个但是这不是引起你问题的问题]
  • 步骤 7 mapArray[i][j] = rnd.nextInt(2); => mapArray[0][0] = rnd.nextInt(2); ...

现在有一些提示可以继续:

The code should cycle through all of the array's elements, giving them a value of either 0 or 1 ( until the number of treasures entered by the user reaches 0 ).

你可以翻译成:我需要把我的X个宝藏放到我的地图里。

所以while循环是个好主意,但实际上用错了地方。删除 2 个 for 循环,只保留 while 循环开头。

现在想办法把这些宝物一个一个地放在地图上的正确位置。

稍后,如果您需要 运行 通过映射,那么您将需要 2 个 for 循环。例如,显示您的地图可能很有用。

不要忘记检查您的输入是否有效。