2015-03-02 106 views
0

我是新來的Java和建立一個骰子游戲,我需要合併兩個骰子,而不是一個。我正在使用roll = r.nextInt(12)+2;但那不會像滾動兩個單獨的骰子一樣產生同樣的可能性。我改變了以下的隨機數,但現在它將輸出翻倍。任何幫助將不勝感激。骰子滾動遊戲模擬器

import java.util.*; 

公共類W7KyleAbel {

public static void main(String[] args) 
{ 
    // Utilities 
    Scanner in = new Scanner (System.in); 
    Random r = new Random(); 

    // Variables 
    int numberOfrolls = 0; 
    int rollOne = 0; 
    int rollTwo = 0; 
    int [] count = new int [12]; 

    //Welcome Statement 
    System.out.println("Welcome to the dice throwing simulator!"); 

    //Get the number of rolls from the user 
    System.out.println("How many dice rolls would you like to simulate?"); 
    numberOfrolls = in.nextInt(); 

    //Simulate the number of rolls 
    for (int i = 0; i < numberOfrolls; i++) 
    { 
     rollOne = r.nextInt(6)+1; 
     rollTwo = r.nextInt(6)+1; 
     count[rollOne+rollTwo]++; 
    } //end for 

    //Iterate through the list of rolled counts & histogram 
    for(int i = 1; i < count.length; i++) 
    { 
     StringBuffer outputBuffer = new StringBuffer(100 * count[i]/numberOfrolls); 
     for (int j = 0; j < count[i]; j++) 
     { 
      outputBuffer.append("*"); 
     }//end for 
     System.out.println((i+1)+ ":" + outputBuffer); 
    }//end for 

    //Results 
    System.out.println("DICE ROLLING SIMULATION RESULTS\n" + 
      "Each \"*\" represents 1% of the total number of rolls.\n" + 
      "Total number of rolls = "+ numberOfrolls + "."); 

}}

+2

肯定你打算寫'count [rollOne + rollTwo] ++;'對嗎? – 2015-03-02 05:29:01

+0

或'count [rollOne + rollTwo-1] ++;',no? – 2015-03-02 06:48:46

+0

工作感謝你! – K455306 2015-03-03 05:26:36

回答

-1

至於什麼大衛Wallance說,這兩個骰子的總和,可以由此實現。

count[rollOne+rollTwo+1]++; 

用千次模擬試驗了代碼,沒有問題。

+1

甚至沒有'ArrayIndexOutOfBoundsException'?我原以爲你會得到至少一個11或12在一千卷...... – 2015-03-02 06:52:20

+0

@James_D不,我用他的代碼剛剛取代2提到的一個計數,結果是正常的。 – Weiest 2015-03-02 07:55:08

+0

@James_D當我輸入的金額高於10時,我收到一個ArrayIndexOutOfBoundsException。例如100或1000.您是否知道爲什麼它可以用於較低的金額? – K455306 2015-03-04 00:52:09

0

由於1<=rollOne<=61<=rollTwo<=6我認爲你需要count[rollOne+rollTwo-1]++;:那麼count[i]將代表的次一共有i+1與兩個骰子被拋出數。