[英]Why does the output for my program always start with two consecutive zeros even though I wrote a code that doesn't produce zeros or repeated numbers?
我正在嘗試創建一種使用隨機數生成器生成彩票號碼的方法。 有兩組數字。 第一組應該具有五個不同的數字,這些數字按排序順序顯示,范圍為1至56。 第二組由范圍為1到46的單個數字組成。 當我運行程序時,即使我試圖以不允許組1包含零或重復數字的方式編寫代碼,組1總是以兩個連續的零開始。 最初,我認為問題一定與隨機數生成器有關,因此我嘗試在NetBeans中調試項目。 當我逐步執行代碼行時,我可以看到分配給n的值,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代替,但是我仍然遇到相同的問題。 有人知道我在做什么錯嗎? 任何和所有建議都將不勝感激。
Arrays.sort(Group1);
造成了問題。
我相信Arrays.sort(Group1);
應該放在第一個for循環之后(生成Group1值之后)。
當前,在將每個值相加后對值進行排序。
最初,數組中的0 0 0 0 0
第一次迭代
生成第一個數字后
n= rand.nextInt(55)+1; //lets assume the generated value is 43
的數組變成43 0 0 0 0
調用排序后,
Arrays.sort(Group1);
數組變為0 0 0 0 43
第二次迭代。
生成第二個數字后
n= rand.nextInt(55)+1; //lets assume the generated value is 22
的數組變為0 22 0 0 43
調用排序后,
Arrays.sort(Group1);
數組變為0 0 0 22 43
第三次迭代
生成第三個數字之后
n= rand.nextInt(55)+1; //lets assume the generated value is 31
數組變為0 0 31 22 43
調用排序后,
Arrays.sort(Group1);
數組變為0 0 22 31 43
第4次和第5次迭代不會更改數組中的前兩個值。 這樣,前2個數字將停留為0,這說明了您的結果。
您不能在未排序的數組上使用Arrays.binarySearch
。 在這種情況下,此操作的結果是不可預測的。
排序將所有零移動到數組的開頭。 但是您沒有重寫它們(因為j
正在遞增)。
我認為問題在於每次對int數組進行排序。 int數組初始化為0。通過在每次更改插入新隨機數的位置時對數組進行排序。 因此,有時您不小心覆蓋了隨機生成的數字之一,而不是0。
也許不是使用BinarySearch,而是要求使用剛剛使用的排序包含並擺脫排序,直到生成所有隨機數。 我不知道確切的語法,因為我已經3年沒有用Java編寫代碼了,但是您可以執行Arrays.asList(Group1).contains(n)之類的操作。 所以...
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;
while (Arrays.asList(Group1).contains(n)) {
n = rand.nextInt(55)+1;
}
Group1[j] = n;
}
Arrays.sort(Group1);
你好,據我所知,有零位數字的情況,一般是默認分配器是零分配器,那是你沒有初始化這個變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.