Reputation: 13
I am trying to give each index of each object "Room" in the 2d array maze a random value between 0 and 9. However, during the for loop where I create each unique room's numbers, it instead gives all rooms the numbers generated for the last room. I am completely stumped.
I have tried allocating the randomization to a new method, and directly changing the indices using "maze[i][j].structure[1][2]" to no avail.
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();
}
}
}
}
Upvotes: 1
Views: 72
Reputation: 160170
You declare structure
as static
–this means there is only one, and you keep overwriting it.
Declare it like your exists
variable, e.g., not static.
Upvotes: 2