我有一個數字數組,其中包含20個元素。我爲黑莓應用程序隨機顯示數字,bt我想要dat所有生成的d數字應該是唯一的。它應該是隨機生成的,它具有唯一性,直到陣列中的所有元素都耗盡。我在這裏給出這段代碼,如果有人能幫助我,我會非常感激。如何從一個數組中隨機生成數字,每個數字都是唯一的
static int quesNum[] = new int[20];
static int quesCount = -1;
private static void initialize(){
Random rgen = new Random(); // Random number generator
//--- Initialize the array
for (int i=0; i<quesNum.length; i++) {
quesNum[i] = i;
}
//--- Shuffle by exchanging each element randomly
for (int i=0; i< quesNum.length; i++) {
int randomPosition = rgen.nextInt(quesNum.length);
int temp = quesNum[i];
quesNum[i] = quesNum[randomPosition];
quesNum[randomPosition] = temp;
}
}
/*Changed the code to get a unique random number
*/
public static int getQuestionNumber() {
quesCount++;
if(quesCount < quesNum.length){
return quesNum[quesCount];
}
else{
initialize();
quesCount = -1;
return getQuestionNumber();
}
}
如果您避免了青少年的縮寫(例如「b」與「be」),我將非常感激。它使閱讀更難。謝謝。 – 2010-06-20 00:25:22