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;
}
}
}
用户指定数组的高度和宽度,以及该数组包含的“宝藏”数量。代码应该循环遍历数组的所有元素,为它们赋予值 0 或 1(直到用户输入的宝藏数量达到 0)。
宝藏指示为1。
现在 for 循环仅针对第一个 ( [0] [0] ) 元素。
最佳答案
您应该消除 while 循环,因为它会阻止 i
和j
从递增直到结束,这就是为什么只有 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。
关于java - 用户指定的二维数组元素值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35573829/