這是解釋遊戲的註釋,所以你可以測試它,但主要問題是當你想運行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);
}
}
}
}
這是一個無限循環?當你推出一個等於7或者這個點的總數時,它將停止。它不會停止,直到達到這些標準之一,你可能應該檢查他們是否有錢。 –
爲什麼你不調試是因爲你測試它?據推測,循環退出條件沒有得到滿足 - 爲什麼不調試它並找出原因? –
爲什麼'rollAgain'是一個循環? –