gpt4 book ai didi

java - 为什么我的int[][]填充的是1而不是0?

转载 作者:行者123 更新时间:2023-12-02 09:57:46 25 4
gpt4 key购买 nike

我正在用一只老鼠在房间里寻找奶酪来完成我的项目。简而言之,我有一个棋盘,里面装满了 0(空)、1(随机奶酪)和 2(随机鼠标)。第一个控制台显示是正确的,但第二个控制台显示从 0 变为 1。知道发生了什么吗?

    Random random = new Random();
int cheese = 53 + random.nextInt(477);
int mouseX = random.nextInt(23);
int mouseY = random.nextInt(23);

int[][] room = new int[23][23];

for(int i = 0; i< room.length; i++) {
for (int j = 0; j < room.length; j++) {
room[i][j] = 0; //empty room

for (int l = 0; l <= cheese; l++) {
int m = random.nextInt(23);
int n = random.nextInt(23);
room[m][n] = 1; //cheese
}
room[mouseY][mouseX] = 2;// mouse

System.out.print(room[i][j] + " ");
}
System.out.println();
}
System.out.println();
System.out.println("Cheese amount: " + cheese);
System.out.println("Mouse position: " + mouseY + ", " + mouseX);

for(int i = 0; i < room.length; i++){
for(int j = 0; j < room.length; j++){
System.out.print(room[i][j] + " ");
}
System.out.println();

最佳答案

我将从描述开始,说明代码在逻辑上的作用。我们将使用 2 个术语,第一个是 tile (放置鼠标、奶酪或任何东西的单个位置)和 room (二维数组由 tiles 组成)。

  1. 创建一些变量(您种植的奶酪数量)+创建 room
  2. 查看完整尺寸的 room对于每个 tile 在两个方向 (X,Y) 上:
    • 设置tile到 0 - 清空它 ( room[i][j] = 0; )
    • 检查所有可用的奶酪数量(从 0 到 cheese 数量):
      • 选择随机 X,Y tile并将其设置为奶酪 ( room[m][n] = 1; )
      • 重复直到所有可用的奶酪凝固
    • 将鼠标设置为随机图 block
    • 重复步骤 2。-> 循环,进行下一个 tileroom
  3. 完成剩下的工作(例如打印数组+结果)
<小时/>

如果从上到下,你会一次又一次地围绕第2点循环。这意味着:

  • 您设置了第一 tile为 0,设置随机量 tiles要成为奶酪,请设置随机鼠标
  • 您设置了第二 tile为 0,设置随机量 tiles要成为奶酪,请设置随机鼠标
  • 您设置了第三 tile为 0,设置随机量 tiles要成为奶酪,请设置随机鼠标
  • ...
  • 您设置了最后 tile为 0,设置随机量 tiles要成为奶酪,请设置随机鼠标
<小时/>

问题很简单,您应该将填充随机奶酪的代码放在 for 下清空字段的周期:

for(int i = 0; i< room.length; i++) {
for (int j = 0; j < room.length; j++) {
room[i][j] = 0; //empty room
}
}

for (int l = 0; l <= cheese; l++) {
int m = random.nextInt(23);
int n = random.nextInt(23);
room[m][n] = 1; //cheese
}

room[mouseY][mouseX] = 2;// mouse
//note that the row above can overwrite already existing cheese, algorithm may need optimization because of that

关于java - 为什么我的int[][]填充的是1而不是0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55868594/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com