首页 > 解决方案 > 随机数只初始化一次

问题描述

我试图给二维数组迷宫中每个对象“房间”的每个索引一个介于 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();
            }
        }
    } 
} 

标签: java

解决方案


您声明structurestatic- 这意味着只有一个,并且您继续覆盖它。

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


推荐阅读