2017-08-09 46 views
3

我想寫一個程序,我滾動兩個死亡,直到我得到那些骰子的總和爲11.我想記錄多少「嘗試」或滾動的骰子我使用我的11爪哇:滾動兩個骰子,直到你得到所需的金額

我的代碼的總和至今的時間:它只是不斷印刷,它花了1卷得到的11之

public class Dice { 

    public static void main(String[] args) { 

    int counter1 = 0; //Amount of rolls player 1 took to get sum of 9 
    int P1sum = 0; 

    do { 
     int P1Die1 = (int)(Math.random()*6)+1; 
     int P1Die2 = (int)(Math.random()*6)+1; 
     P1sum = (P1Die1 + P1Die2); 
     counter1++; 
    } while (P1sum == 11); 

     System.out.println("Player 1 took "+counter1+" amount of rolls to have a sum of 11."); 
    } 
} 

,這樣的東西是不對的。

我的目標:讓玩家1繼續滾動2死,直到我得到11的總和,並記錄它花了多少次嘗試。然後讓玩家2也這樣做。那麼無論哪個玩家的嘗試次數較少都會贏得比賽。

幫助表示讚賞感謝我是一個新手

+6

你的條件是錯誤的,它應該是''而不是'而(P1sum == 11)(P1sum = 11!) ' – spuente

回答

8

您可能需要更新您的狀態

while (P1sum == 11) // this results in false and exit anytime your sum is not 11 

while (P1sum != 11) // this would execute the loop until your sum is 11 
1

考慮,即Math.random()返回浮點數0 <= x <= 1.0Java API docs Math.random()) 。所以,你的公式中的最大值:

(int)(Math.random()*6)+1; 

等於7