2013-11-29 41 views
1

這是解釋遊戲的註釋,所以你可以測試它,但主要問題是當你想運行while循環時,如果你有一個點值,那麼它就成爲一個無限循環。我如何讓它不是一個無限循環?胡扯遊戲:我如何從這個代碼中進入無限循環的while循環?

import java.util.Random; 

public class Craps { 
    private int roll1; 
    private int roll2; 
    private Random randGen; 
    private int sum; 
    private int thePoint = sum; 
    private int bet; 
    private int newSum; 

    // instance classes 
    public Craps() { 
     randGen = new Random(); // this is the random generator 
    } 

    // when you win you double your money 
    // when you lose you lose everything 
    public void roll(int bet) { // you can bet as much money as you want 
     roll1 = (randGen.nextInt(6) + 1); 
     roll2 = (randGen.nextInt(6) + 1); 
     sum = roll1 + roll2; // you must add the two rolls and that is your sum 
     if (sum == 2 || sum == 3 || sum == 12) { // if the sum is 2 you lose 
      System.out.println("The sum is 2. You Lose!"); 
      System.out.println("Your credit:" + " " + bet * 0); 
     } else if (sum == 7 || sum == 11) { // if it 7 you win 
      System.out.println("The sum is 7. You Win!"); 
      System.out.println("Your credit:" + " " + bet * 2); 
     } else { 
      System.out.println("You rolled a" + " " + sum + ". " + "That is your point. Roll  again."); 
      sum = thePoint; 

     } 
    } 

    public void rollAgain() { 

     while (sum != 7 || sum != thePoint) { // whatever the the sum is that is not one of the numbers above becomes your point. 
      roll1 = (randGen.nextInt(6) + 1);// you must role the die again until you get your point again the you win or until you get a 7 and then you lose. 
      roll2 = (randGen.nextInt(6) + 1); 
      sum = roll1 + roll2; 
      if (thePoint == sum) { // if the point equals the sum you win 
       System.out.println("You're on point. You Win!"); 
       System.out.println("Your credit:" + " " + bet * 2); 
      } else if (sum == 7) { // if it equals 7 you lose. 
       System.out.println("You got a 7. You lose!"); 
       System.out.println("Your credit:" + " " + bet * 0); 
      } 
     } 
    } 
} 
+0

這是一個無限循環?當你推出一個等於7或者這個點的總數時,它將停止。它不會停止,直到達到這些標準之一,你可能應該檢查他們是否有錢。 –

+0

爲什麼你不調試是因爲你測試它?據推測,循環退出條件沒有得到滿足 - 爲什麼不調試它並找出原因? –

+0

爲什麼'rollAgain'是一個循環? –

回答

0

您需要更改環路條件。

while (sum != 7 || sum != thePoint)這裏發生的事情是,只要滿足第一個條件(總和不是7),循環開始執行。

如果將其更改爲while (sum != 7 && sum != thePoint),則需要滿足這兩個條件 - 如果總和不是7或值爲thePoint,則循環只會再次開始執行。

+0

但我只需要滿足這些條件之一。如果新捲成爲7,那麼它假設是一個失敗者,但是如果它成爲第一個卷的總和,那麼它就是一個勝利。我是否需要爲每種情況製作單獨的報表? – user3047661