2015-05-12 103 views
1

我想知道如何讓我的骰子滾動模擬器停止,當你的總滾動是2個確定的數字之一,(例如:當你達到7或12的總滾動時滾動將停止)。這是我到目前爲止的代碼:骰子滾動模擬

public class RollDice { 

    public static void main(String[] args) { 
     // TODO Auto-generated method stub 

     int dice1; // First Dice. 
     int dice2; // Second Dice. 
     int total; // Sum of the two rolls. 

     dice1 = (int)(Math.random()*6) + 1; 
     dice2 = (int)(Math.random()*6) + 1; 
     total = dice1 + dice2; 

     System.out.println("Your first roll is " + dice1); 
     System.out.println("Your second roll is " + dice2); 
     System.out.println("Your complete roll is " + total); 

    } 

} 

回答

3

只是包裝一切有do-while循環:

int total; // Sum of the two rolls. 
do { 
    int dice1; // First Dice. 
    int dice2; // Second Dice. 

    dice1 = (int)(Math.random()*6) + 1; 
    dice2 = (int)(Math.random()*6) + 1; 
    total = dice1 + dice2; 

    System.out.println("Your first roll is " + dice1); 
    System.out.println("Your second roll is " + dice2); 
    System.out.println("Your complete roll is " + total); 
} while (total != 7 && total != 12); 

或者其他類似的程度。 :)

https://docs.oracle.com/javase/tutorial/java/nutsandbolts/while.html

+0

出於某種原因,它不會讓我解決總在最後一行的變量,這是爲什麼? – hallibtch

+0

對啊,對不起,打字太快了。回答編輯.. :) –

+0

完美!謝謝。 – hallibtch