首页 > 解决方案 > 在 Java 中将 20 个随机宝藏插入 10 x 10 网格中

问题描述

我创建了一个 10 x 10 并有 100 个按钮的 GUI。我必须插入 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]);
        }

标签: javaswingjbutton

解决方案


  1. 创建一个数组列表
  2. 将 20 个 TreasureButton 实例添加到 ArrayList
  3. 将 80 个 EmptyButton 实例添加到 ArrayList
  4. 使用 Collections.shuffle(...) 随机化按钮。
  5. 遍历 ArrayList 并将每个按钮添加到面板

推荐阅读