出于某种原因,我认为我的脚本正在无限循环,我无法弄清原因。
我有一个带有40个棋子的数组,需要将它们随机放在板上。
所以我有一个随机数,它从数组中选择一个随机的pawn,但是如果已经选择了pawn,它就必须选择一个新的随机数,但是最后一部分似乎由于某种原因而出错。
我不知道为什么。
Random rand = new Random();
int[] availablePawnsArray = {1, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 8, 8, 9, 10, 11, 12, 12, 12, 12, 12, 12 };
// this array contains 40 integers
int[] chosenPawns = new int[40];
//this array contains the index numbers of already selected pawnsfrom the previous array
int counter = 0;
//counts how many pawns have been selected already
for (int i = 0; i < 4; i++) {
for (int j = 0; j < 10; j++) {
//this refers to my board, 40 locations for my 40 pawns
int chosenPawn = rand.nextInt(40);
//a random numder from 0 to 40
boolean found = false;
//a boolean to say if i have already selected this pawn before or not
do {
for (int n : chosenPawns) {
if (n == chosenPawn) {
found = true;
chosenPawn = rand.nextInt(40);
} else {
found = false;
}
}
} while(found == true);
board[i][j].rank = availablePawnsArray[chosenPawn];
chosenPawns[counter] = chosenPawn;
counter++;
}
}
最佳答案
您可以有两个数组,第二个数组保留选定的整数,然后在第二个数组中循环检查是否有任何数字等于给定的一个,返回false或true。
int [] selectedInts = new int[40];
boolean contains(int num) {
for (int i = 0 ; i < selectedInts.length; i++) {
if (i == num) return true;
}
return false;
}
你也可以像
Arrays.asList().contains(yourInt);