java - 随机数只初始化一次
问题描述
我试图给二维数组迷宫中每个对象“房间”的每个索引一个介于 0 和 9 之间的随机值。但是,在我创建每个唯一房间的数字的 for 循环期间,它改为为所有房间提供为最后一个房间。我完全被难住了。
我尝试将随机化分配给一种新方法,并使用“maze[i][j].structure[1][2]”直接更改索引无济于事。
public class Room {
static int[][] structure;
boolean exists;
// Constructor Declaration of Class
public Room(int[][] structure, boolean exists)
{
this.structure = structure;
this.exists = exists;
}
public static void main(String[] args) {
Room[][] maze = new Room[3][3];
// setup array of rooms
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
int a = (int)(Math.random()*9);
int b = (int)(Math.random()*9);
int c = (int)(Math.random()*9);
Out.println(a + ", " + b + ", " + c);
int[][] roomBuild = {{1,1,1,1,1},
{1,a,b,c,1},
{1,1,1,1,1}};
maze[i][j] = new Room(roomBuild, true);
//int[] nums = Logic.genRoom();
//maze[i][2].structure[1][1] = nums[0];
//maze[i][2].structure[1][2] = nums[1];
//maze[i][2].structure[1][3] = nums[2];
}
}
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
for (int k=0; k<3; k++) {
for (int l=0; l<5; l++) {
System.out.print(maze[i][j].structure[k][l]);
}
Out.println();
}
Out.println(i + "," + j + ", " + maze[i][j].exists);
Out.println();
}
}
}
}
解决方案
您声明structure
为static
- 这意味着只有一个,并且您继续覆盖它。
exists
像你的变量一样声明它,例如,不是静态的。
推荐阅读
- c# - C# - 通过创建日期和 UNIX Cron 表达式获取上次作业执行的日期
- google-data-studio - Vega-Lite 中用于甘特图的滚动条 - Data Studio
- javascript - 混合 Node 的 CommonJS 和 Typescript 的 ES 模块
- redis - AWS Redis 集群模式 - 自动故障转移和多可用区标志有什么区别?
- r - 例如:计算当 x[i]>0 时为真的逻辑向量
- r - 如果闪亮的应用程序用户想要不同的方式来选择人员级别的数据进行可视化,多个“选择”控件小部件如何同步在一起?
- dotnetnuke - DNN Cookie 弹出窗口未显示 - 无法读取未定义的属性(读取“getVAR”)
- c# - 我收到以下错误:在模型中将公共字符串更改为公共动态后,“表达式树可能不包含动态操作”
- node.js - 如何使用 Mongoose 和 Nodehs 更新 MongoDB 中的字段列表?
- excel - VBA中的Excel函数