2013-05-02 32 views
2
int num = 10; 
Random rand = new Random(); 
    int ran = rand.nextInt(num); 
    if (ran==0){ 

     ran= ran+1; 
    } 
    else{ 
     System.out.println("random : "+ran); 
    } 

這是我編碼到目前爲止,有沒有更好的方法來做到這一點?我覺得這是硬編碼,當隨機是0時,我加1。Java隨機數但不爲零

+1

你的邏輯看起來是錯誤的。如果這個數字是'0',那麼你將隨機數字增加'1',但是不會打印出這個值。同樣在你的例子'1'中,出現任何其他數字 – 2013-05-02 07:59:34

回答

19

該代碼的問題是,1的可能性是其他數字的兩倍(因爲當nextInt()返回0或1時,您的有效結果爲1)。

最好的解決方法就是總是從一個較小的範圍內添加1支,請求隨機數:

int rnd = rand.nextInt(num - 1) + 1; 
+0

的可能性是maxValue-1的兩倍。我在這裏指定的數字是? – newbieprogrammer 2013-05-02 07:59:32

+2

maxValue是您將獲得的最大隨機數。因爲您稍後添加一個,您必須請求maxValue-1 – vszurma 2013-05-02 08:04:04

+0

如果'maxValue'確實是您獲得的最高數字,那麼'-1'錯誤,因爲'nextInt(10)'返回範圍爲0的數字。 .9'。因此我編輯答案。 – Vlasec 2014-12-11 16:03:13

2
Random random = new Random; 
int ran = random.nextInt(9) + 1; //10 is maxRandom value for this code. 1-10 
+0

so meaning,random.nextInt(num-1)+ 1? – newbieprogrammer 2013-05-02 08:00:40

+1

@ newbieprogrammer'random.nextInt(maxValue)+ 1''maxValue'設置從** 0 **到'maxValue'的範圍。所以如果'maxValue'等於9,你的最大整數將是10. – 2013-05-02 08:06:49

+1

random.nextInt(9)+ 1會給你1-9。 – CptSupermrkt 2013-10-21 01:04:21

3

我想你想得1和「民」之間的隨機數。

一個更通用的方法可以是:

int Low = 1; 
int High = 10; 
int R = r.nextInt(High-Low) + Low; 

這使您在之間的隨機數1(含)和10(不含)。 (或使用高= 11 10含)

+0

這讓人感到困惑。我只是想要10中的隨機數,但不是0。 – newbieprogrammer 2013-05-02 08:03:44

+0

讓我知道什麼部分讓你困惑,會盡力解釋 – Lav 2013-05-02 08:08:52

+0

讓我說我想從1到小於10的隨機數。 我應該指定哪個數字? – newbieprogrammer 2013-05-02 08:11:55

1

你也可以做到以下幾點:

int randomNumber = 0; 
do { 
    randomNumber = rand.nextInt(maxValue); 
} while(randomNumber == 0); 
0

不要指望從Random此功能,並自己做,你應該。一個人可以做任何事情的結果 - 乘,加(例如2*nextInt(n)+1爲隨機奇數),使用對數尺度音符頻率,使用地圖或枚舉獲得隨機對象...

方法nextInt(n)在這裏只給你n不同的值(從0n-1)。不要問更多,自己去實施其餘的。如果我理解你的問題,你需要號碼1..9,所以你應該要求nextInt(9)+1得到0..8,然後添加1

我希望這個解釋有幫助,我看到很多答案,但我不喜歡在其中的任何解釋。

-1

嘗試:

int num = 10; 
Random rand = new Random(); 
int ran = rand.nextInt(num) + 1;