我想創建一個隨機數生成器產生抽獎號碼的方法。有兩組數字。第一組應該有五個不同的數字,按照排序順序顯示,範圍爲1-56。第二組由一個範圍爲1-46的單個數字組成。當我運行程序時,組1總是開始兩個連續的零,即使我試圖以不允許組1有零或重複數字的方式編寫代碼。起初我認爲這個問題必須與隨機數生成器有關,所以我嘗試在NetBeans中調試項目。當我通過代碼行時,我可以看到賦值給n的值,這是保存隨機生成器生成的數字的變量。 n的值是54,50,11,49和28.在該程序中,n的值被放入一個有序數組中。所以輸出組一個本來應該是11,28,49,50,54,而是它是0,0,11,28,49爲什麼我的程序輸出總是以兩個連續的零開始,即使我寫了一個不產生零或重複數字的代碼?
這裏是我的代碼:
public static void MakeTickets(){
int [] Group1= new int [5];
int Group2;
int n;
Random rand= new Random();
for (int j=0 ; j<5; j++){
//Here, I try to make sure that the range for n is 1-56
n= rand.nextInt(55)+1;
//Here, I try to make sure that a number isn't put into the group one
//array more than once
while (Arrays.binarySearch(Group1, n)>=0){
n= rand.nextInt(55)+1;
}
Group1[j]=n;
Arrays.sort(Group1);
}
Random r= new Random();
int num= r.nextInt(45)+1;
Group2=num;
System.out.print("Here is your ticket: Group One= ");
for(int number: Group1){
if (number==Group1[4]){
System.out.print(number);
} else {
System.out.print(number+", ");
}
}
System.out.println(" Group Two= "+Group2);
}
這裏是輸出:
Here is your ticket: Group One= 0, 0, 33, 45, 50 Group Two= 40
我試過使用ThreadLocalRandom來代替,但我仍然有同樣的問題。有誰知道我做錯了什麼?任何和所有的建議非常感謝。
雖然,將循環移出循環會導致用於防止重複失敗的二進制搜索。在索引'0'而不是'j'中插入可以工作,或者既可以移動排序又可以切換到線性搜索。 – Douglas