首页 > 解决方案 > Java:掷骰子游戏:退出循环然后重新进入

问题描述

这是一个模拟骰子游戏Craps的程序。规则是,如果你掷出 7 或 11,你就赢了。如果您掷出 2、3 或 12,则您输了。如果您滚动其他任何东西,您将获得“点”并被允许再次滚动。如果你分配 2 分,你也赢了。

我在这里遇到的麻烦是积分系统。我不知道如何存储该点,然后退出循环并提示用户再次滚动以重新进入循环。

import javax.swing.JOptionPane;

public class DiceGame {

    public static void main(String args[ ]) {

        // declarations

        int dieNumber1,
                dieNumber2,
                point,
                score;

        // initializations

        dieNumber1 = (int)(Math.random( ) * 6 + 1);
        dieNumber2 = (int)(Math.random( ) * 6 + 1);
        score = dieNumber1 + dieNumber2;  

        // executable statements

        for (int i = 0; i < 10000; i++)
        {

            System.out.println ("Roll the die");
            System.out.println ("You rolled a " + score);

            if (score == 11 || score == 7)
            {
                System.out.println ("You Win!");
                break;
            }

            if (score == 2 || score == 3 || score == 12)
            {
                System.out.println ("You Lose.");
                break;   
            }

            if (score == 4 || score == 5 || score == 6 || score == 8 || score == 9 || score == 10)
            {
                point = 1;
                System.out.println ("You got a point.");
            }


        }


        System.exit(0);

    } // end of the main method

} // end of the class 

标签: java

解决方案


您可能需要明确考虑程序的流程应该如何运行。即:每卷有三种结果:赢、输、分。我们什么时候想循环?我假设(你的答案可能不同)当我们想再次滚动时。我们什么时候想再次滚动?我假设(你的答案可能不同)当用户得到一个点时。因此,重点案例应该是我们循环的结果,任何其他结果都应该导致循环。

请注意,因为我们总是需要在进行任何其他逻辑之前进行滚动(如果我们不滚动,则无法决定赢/输/分),我们将滚动逻辑放在循环中:

那么我们的代码会是什么样子呢?

import javax.swing.JOptionPane;

public class DiceGame {

    public static void main(String args[ ]) {

        // Initialize some things (omitted)

        while(true) { // NOTE: it's generally good form to use while(true) for a loop that could continue forever, instead of a for-loop with a very high number
            // Roll the dice (omitted)
            if (score == 11 || score == 7)
            {
                System.out.println ("You Win!");
                break; // Game over. Get out of our infinite loop.
            }
            if (score == 2 || score == 3 || score == 12)
            {
                System.out.println ("You Lose.");
                break; // As above
            }
            else // If our score is anything else we must have gotten a point
            {
            point = 1; // Don't break. We want to roll again
            }
        }
    }
}

推荐阅读