我正在製作一個類的程序,它要求程序在1-40範圍內創建6個隨機生成的整數,並將它們放入數組中。整數必須是唯一的,這樣就不會出現一定數量的重複情況。然後將該數組傳遞到另一個按照升序對數組進行排序的方法。我的問題是,我無法讓我的代碼生成6個唯一的數字。我的代碼如下:防止數組中的重複整數
private static void getComputer(int computerNumbers, int[] cN)
{
Random randomNumbers = new Random();
for (int i = 0; i < computerNumbers;)
{
int computerStored = randomNumbers.nextInt(39)+1;
if (computerStored == cN[0] || computerStored == cN[1] || computerStored == cN[2] ||
computerStored == cN[3] || computerStored == cN[4] || computerStored == cN[5])
continue;
else
computerStored = cN[i];
i++;
}
}
上面的代碼塊輸出的0,0,0,0,0,0陣列。我只是無法找出原因。任何幫助將非常感激。謝謝。
只是澄清,我知道如何做一個基本隨機生成器。
private static void getComputer(int computerNumbers, int[] cN)
{
Random randomNumbers = new Random();
for (int i = 0; i < computerNumbers; i++)
cN[i] = randomNumbers.nextInt(39)+1;
}
WOW。這樣的小差別真的可以成爲答案嗎?我試過了,它工作。謝謝。爲什麼這能解決問題? – user3577449
@ user3577449'computerStored = cN [i]'意味着「將'cN [i]'的值放入'computerStored''中,另一種方式意味着」將'computerStored'的值放入'cN [i]'「 。編程指令非常具體,計算機將完全按照你所說的去做,而不是你想說的但不是。 – chrylis
它解決了這個問題,因爲你通過將生成的'computerStored'值放置在=運算符的左側來重新賦值。所以數組從未被更新。 –