java - 在 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]);
}
解决方案
- 创建一个数组列表
- 将 20 个 TreasureButton 实例添加到 ArrayList
- 将 80 个 EmptyButton 实例添加到 ArrayList
- 使用 Collections.shuffle(...) 随机化按钮。
- 遍历 ArrayList 并将每个按钮添加到面板
推荐阅读
- android - 为什么用jsoup解析后img标签没有src值?
- latex - \afterpage 和 \endfloat
- javascript - 如何绕过请求限制?
- javascript - how can i fix my javascript calculation which is not working?
- python - 如何将我自己的模块导入到一个scrapy项目中?
- css - 如何将 INSPINIA 引导程序添加到 Ember 应用程序
- php - .htaccess HTTPS 重定向工作,但 HTTPS 去 /index.php
- java - 我的外键没有被插入到数据库中,知道我做错了什么吗?
- php - 尝试在 cPanel 上运行 localhost 网站时出错
- laravel - ManyToMany with 和 whereIn