随机数仅初始化一次

时间:2019-10-18 19:08:55

标签: java

我正在尝试为2d数组迷宫中的每个对象“ Room”的每个索引提供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();
            }
        }
    } 
} 

1 个答案:

答案 0 :(得分:2)

您将structure声明为static –这意味着只有一个,并且您将其覆盖。

像您的exists变量一样声明它,例如,不是静态的。