2017-03-14 133 views
-1

雖然試圖創建一個Coin對象類使用兩個特定的種子在創建時傳遞到對象,我注意到,當將種子傳遞給一個int「seed」時,seed變量產生一個而不僅僅是將特定數字輸入到隨機數生成器中。下面是從硬幣類的一些代碼:Java隨機生成器的種子產生不同的輸出

public int headCount; 
public int tailCount; 
public int seed; 

public Coin(int n){ 
    seed = n; 
    headCount = 0; 
    tailCount = 0; 
} 
public Random flipGenerator = new Random(seed); 

public String flip(){ 
    String heads = "H"; 
    String tails = "T"; 

    boolean nextFlip = flipGenerator.nextBoolean(); 
    if (nextFlip == true) 
    { 
     headCount++; 
     return heads; 
    } 
    if (nextFlip == false) 
    { 
     tailCount++; 
     return tails; 
    } 
    return null; 
} 

這裏從創建和打印硬幣對象的文件是:

Coin coin1 = new Coin(17); 
Coin coin2 = new Coin(13); 

在該文件中打印出隨機結果的代碼中使用翻轉20次17號種子,13號種子10次,最後35次17號種子。但是輸出使用

public Random flipGenerator = new Random(seed); 

,而不是

public Random flipGenerator = new Random(17); 

public Random flipGenerator = new Random(13); 

這是怎麼回事時,是不正確?

+5

初始化flipGenerator裏面的構造函數,種子之後。否則種子的默認值爲0. – Squiddie

+1

什麼構成「不正確」?但是,您是否嘗試過在調試器中運行並查看變量的初始化?如果要將flipGenerator移動到構造函數中,會發生什麼情況? – KevinO

回答

2

實例字段在調用構造函數之前被初始化。

在執行順序而言,此代碼:

public int headCount; 
public int tailCount; 
public int seed; 

public Coin(int n){ 
    seed = n; 
    headCount = 0; 
    tailCount = 0; 
} 
public Random flipGenerator = new Random(seed); 

在功能上等效於這樣的:

public int headCount; 
public int tailCount; 
public int seed; 
public Random flipGenerator = new Random(seed); 

public Coin(int n){ 
    seed = n; 
    headCount = 0; 
    tailCount = 0; 
} 

在Java中,其沒有明確初始化任何字段中給出的值爲零/ null/false,所以你總是flipGenerator = new Random(0)。在您的構造函數中初始化seed時,Random對象已經創建。實例字段在構造函數之後聲明是不相關的,因爲所有實例字段及其初始化表達式都是在調用構造函數之前執行的。

0

每當初始化​​類時,它將使用0作爲種子。無論如何將flipGenerator初始化放在構造函數下面,它仍然會在構造函數中被調用,因爲它是一個實例變量。

Coin coin1 = new Coin(17); 
Coin coin2 = new Coin(13); 

因爲,你通過種子的時候,flipGenerator與0

默認種子初始化該代碼使用0您需要這樣做

public int headCount; 
    public int tailCount; 
    public int seed; 
    public Random flipGenerator; 

    public Coin(int n){ 
     seed = n; 
     headCount = 0; 
     tailCount = 0; 
     flipGenerator = new Random(seed); 
    } 
    ... 
} 
相關問題