2016-07-11 73 views
-4

我試圖爲我的任務的這一部分生成一個隨機double
問題是 「每週,每個10周齡以上的女性Guppy有25%的產卵機會」。生成隨機對象以獲取java產生

我想生成一個隨機double來確定是否每個女性Guppy應該產卵或不產卵。

我迄今爲止代碼:

Random r = new Random(); 
if (isFemale == true && getAgeInWeeks() >= 10) { 
    //? 
} 
+0

當你看看'隨機'的方法時,你認爲哪種方法最適合你有25%的概率?你爲什麼這麼認爲? *提示:大多數'nextXxx()'方法都適合。* – Andreas

+0

亞這就是我認爲,但我真的很困惑如何輸入編碼我讀隨機和下一個確實出來,但我很困惑 –

回答

1

我看不出有任何理由,以根據您的問題隨機雙。你需要的是一個從0到3的整數,其中每個數字佔產卵的25%。

Random r = new Random(); 
if (isFemale == true && getAgeInWeeks() >= 10) { 
    // Generate a random integer in [0,3] 
    // Since there is a 25% or 1/4 chance 
    if(Math.abs(r.nextInt()) % 4 == 1){ 
     //Note that the 1 in the condition can be replaced by any 
     // integer in [0,3] 
     //Put spawning code here 
    } 
} 

退房此鏈接的詳細信息,隨機: Random (Java Platform SE 7

+2

使用'nextInt(4)'而不是'nextInt()'用模運算符。前者是正確的隨機數,但後者不是Integer.MAX_VALUE不是最大值的倍數。 –

1

生成隨機double,你可以看看this question,但是,這個問題可以更容易地通過生成隨機int小號解決。

在你的情況,產生3int之間0到是你想要的,因爲檢查,如果它是0會的時間(價值1/4可能值= 25%)真正的25%。

編輯:如果你還想生成一個隨機數,看看Guppy將有多少產卵使用threadLocalRandomInstance.nextInt(int bound);像以前一樣。

這些約束可以被轉換成這樣的代碼:

import java.util.concurrent.ThreadLocalRandom; 

public class Test { 
    public static void main(String[] args) {   
     ThreadLocalRandom tlr = ThreadLocalRandom.current(); 

     int num = tlr.nextInt(3 + 1); //Bound is exclusive so add 1. 
     int spawn; 

     if(num == 0) { 
      spawn = tlr.nextInt(100 + 1); //Again, bound is exclusive so add 1. 
     } else spawn = 0; 

     System.out.println("This guppy had " + spawn + " spawn."); 
    } 
} 

我使用ThreadLocalRandom,因爲它是由this answer作爲支持更簡單。
如果您不使用Java 1.7+,請使用Random#nextInt(int),而不是如that answer所示。

+0

基本上說0至100個嬰兒與每個產卵 –