在java中将20个随机宝藏插入一个10 x 10的网格中

zqdjd7g9  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(301)

这个问题在这里已经有答案了

用java生成唯一的随机数(21个答案)
上个月关门了。
我创建了一个10 x 10的gui,有100个按钮。我不得不插入20个宝藏,让其他80个是空的。这是我用的密码。有时我得到17件宝物,有时18件,有时19件。我该怎么解决这个问题?
先谢谢你。

Random random = new Random();
        for (int index = 0; index < 20; index++)
        {
            int insertionIndex = random.nextInt(99)+1;
            buttonGrid[insertionIndex] = new TreasureButton(treasureGame, this);
        }
        // Loop to add EmptyButton()'s into remaining null indexes within the buttonGrid
        for (int index = 0; index < 100; index++)
        {
            // if the current index is null, add an EmptyButton() into it
            if (buttonGrid[index] == null)
            {
                buttonGrid[index] = new EmptyButton(treasureGame, this);
            }
        }
        // Loop to add all of the contents of the buttonGrid into the gamePanel
        for (int index = 0; index < 100; index++)
        {
            gridPanel.add(buttonGrid[index]);
        }
uqxowvwt

uqxowvwt1#

创建arraylist
向arraylist添加20个Button示例
将80个emptybutton示例添加到arraylist
使用collections.shuffle(…)将按钮随机化。
遍历arraylist并将每个按钮添加到面板

相关问题