Craps游戏:如何让这段代码中的while循环进入无限循环?

时间:2013-11-29 00:39:26

标签: java while-loop infinite-loop

这是解释游戏的注释,因此您可以对其进行测试,但主要问题是当您想要运行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);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

您需要更改循环条件。

while (sum != 7 || sum != thePoint)这里发生的是,只要满足第一个条件(sum不是7),循环就会开始执行。

如果将其更改为while (sum != 7 && sum != thePoint),则需要满足这两个条件 - 如果sum不是7或thePoint的值,则循环仅再次开始执行。