我正在完成我在Java编程课程中分配的任务,而且我对Java很新。只要你没有触发do while语句就会在程序中运行正常,当它开始失控时说“你滚动:7你输了”。< / p>
import java.util.Scanner; //Importing the java.util class Scanner
public class Craps {
private Die die1;
private Die die2;
public Craps() {
die1 = new Die();
die2 = new Die();
}
private void rollDice() {
die1.roll();
die2.roll();
}
private int getSum() {
return die1.getNumber() + die2.getNumber();
}
private int getSum2() {
return die1.getNumber() + die2.getNumber();
}
public void playRound() {
rollDice();
int sum = getSum();
int sum2 = getSum2();
System.out.println("You rolled: " + sum);
if (sum == 7 || sum == 11) {
System.out.println("You Win");
}
if (sum == 2 || sum == 3 || sum == 12) {
System.out.println("You Lose");
} else if (sum == 4 || sum == 5 || sum == 6 || sum == 8 || sum == 9 || sum == 10) {
System.out.println("Establishing the point, Re-rolling...");
rollDice();
sum2 = getSum2();
do {
if (sum2 == 7) {
System.out.println("You rolled: " + sum2);
System.out.println("You lose");
}
if (sum2 == sum) {
System.out.println("You rolled: " + sum2);
System.out.println("You win!!!");
}
}
while (sum2 != sum || sum2 != 7);
}
}
public static void main(String[] args) {
Craps game = new Craps();
System.out.println("Welcome to the game of Craps!!!");
System.out.println("Rules: ");
System.out.println("Rolling a 7 or 11 will win you the game");
System.out.println("Subsequently rolling 2, 3, or 12 will lose you the game");
System.out.println("If you roll a 4, 5, 6, 8, or 10 you will 'Establish the point'");
System.out.println("Establishing the point allows you to set a new winning number and reroll");
System.out.println("When you establish the point, the goal is to not roll a 7 and instead roll");
System.out.println("the established number, rolling after establishing a point 7 now will");
System.out.println("result in a loss");
String ans = null;
Scanner scan = new Scanner(System.in);
do {
game.playRound();
ans = scan.nextLine();
}
while (ans.equalsIgnoreCase("Yes"));
}
}
编辑我的模具课程
import java.util.Random;
public class Die {
private int number;
private Random generator;
public Die() {
generator = new Random();
roll();
}
public int getNumber() {
return number;
}
public void roll() {
number = generator.nextInt(6) + 1;
}
}
答案 0 :(得分:1)
sum
和sum2
永远不会在您的do / while循环中更新,所以一旦进入循环,您就永远不会离开它。
do {
if (sum2 == 7) {
System.out.println("You rolled: " + sum2);
System.out.println("You lose");
}
if (sum2 == sum) {
System.out.println("You rolled: " + sum2);
System.out.println("You win!!!");
}
}
while (sum2 != sum || sum2 != 7); // Condition never changes
另一个不错的模式是利用return
进行短路:
while (true) {
rollBabyRoll();
if (getSum2() == 7) {
// Log
return;
else if (getSum() == sum) {
// Log
return;
}
}
<强>加成强>
作为另一个小小的提示,我根本不了解Craps,但你可能想要考虑使用递归。
private void reroll(int sum) {
rollDice();
int sum2 = getSum2();
if (sum2 == 7) {
// Do something
else if (sum2 = sum) {
// Do something
} else {
reroll(sum);
}
}