java试图通过使用嵌套循环获取非重复数字。。(二维阵列)
我试图找到一种方法,可以将随机数插入到一个5x5的二维数组中。我正在制作一款宾果游戏,如果有人能帮我,我将不胜感激。我对Java相当陌生,所以任何帮助都会很好。谢谢
考虑:
boolean matchFound; // used to track when a repeat is found
int rand; // temporarily store the random number before putting it into the array to check if it's a repeat
Random rn = new Random();
for (int i = 0; i < 25 ; i++) {
rand = rn.nextInt(15) + 1;
matchFound = false; // assume that the number generated is not a repeat
for (int x = 0; x <= 5; x++) {
for (int j = 0; j <= 5 ; ++j){
if (rand == b[x][j]) { // check if the number just generated is a repeat
matchFound = true; // if it is, set the boolean to True and use that after the loop
}
if (matchFound == true) { // if the last number is a repeat, then
i = i - 1; // reduce the loop counter by 1 to go back to that place for the new number
} else {
b[i][j] = rand; // the number was not repeated so insert it.
}
}
}
}
# 1 楼答案
在宾果游戏中,你需要追踪列数,以获得每列的正确范围边界(下面代码中的最小值和最大值)
对于列值的外部循环中的每次迭代,这些值都会相应地改变
输出
# 2 楼答案
我建议你把它当作宾果游戏——你有一组数字,随机化,然后为棋盘选择数字。我相信宾果游戏的范围是1-75?但你可以改变这一点。然后从ArrayList中选择前25个数字,它们肯定是随机的,不会以这种方式重复