【问题标题】:about game of craps homework [closed]关于掷骰子作业的游戏[关闭]
【发布时间】:2017-08-13 19:46:28
【问题描述】:

这是我第一次在这里提问。 我是 Java 新手,我对这段代码中的循环有疑问 我不知道在哪里打破循环。

谢谢你帮助我 :) this image is from the book regarding this question

import java.util.*;


     public class GameOfCraps {



    public static void main(String[] args) {
    Random rn = new Random();
    int counterw = 0;
    int counterl = 0;
    int countsum = counterl + counterw;
    int points = 0;

    do {
        int rndice1 = rn.nextInt(5) + 1; // 1 to 6
        int rndice2 = rn.nextInt(5) + 1;// 1 to 6
        int sum = rndice1 + rndice2;// sum of dice random

        if (sum == 2 || sum == 3 || sum == 12) {
            // System.out.println("you lose");
            counterl++;
        }

        else if (sum == 7 || sum == 11) {
            // System.out.println("you won");
            counterw++;

        }

        else {
            do {
                boolean xc = false;
                points = sum;
                int rndice3 = rn.nextInt(5) + 1;
                int rndice4 = rn.nextInt(5) + 1;

                if (rndice3 + rndice4 == points) {
                    // System.out.println("you won");
                    counterw++;
                    xc = true;
                    //break;
                }

                if (xc == false)
                    counterl++;

            } while (points != 7);

        }

    } while (countsum <= 10000);
    System.out.println(counterw);
    System.out.println(counterl);
    System.out.println("probability of winning the game: "+(double)(counterw)/(counterw+counterl));

}

}

【问题讨论】:

  • 这里的实际问题是什么?预期结果是什么,目前的结果是什么?在我看来,您根本不了解 do{]while() 的工作原理?
  • 欢迎来到 Stack Overflow!看起来你可能正在寻求家庭作业帮助。虽然我们对此本身没有任何问题,但请注意这些dos and don'ts,并相应地编辑您的问题。 (即使这不是家庭作业,也请考虑建议。)

标签: java loops if-statement random


【解决方案1】:

问题出在“第二阶段”游戏逻辑中,游戏在获胜后继续进行,每次掷骰后您都会增加损失计数器,而实际上只有首先掷出 7 才应该是失败,然后那场比赛结束。你可能想要更多这样的东西:

    else {
        while (true) {
            int rndice3 = rn.nextInt(5) + 1;
            int rndice4 = rn.nextInt(5) + 1;

            if (rndice3 + rndice4 == sum) {
                // System.out.println("you won");
                counterw++;
                break;
            }

            if (rndice3 + rndice4 == 7) {
                counterl++;
                break;
            }
        }
    }

【讨论】:

  • 我通过将循环从 do{} while {} 更改为 for(){} 来修复代码
【解决方案2】:

在我看来,您可以只使用boolean xc 退出循环而不是使用点语句(鉴于玩家获胜,我假设循环不应该再次运行)

现在 do{}while() 循环像这样工作

do 中的代码总是运行 ATLEAST 1 次,然后检查最后的 while 语句,如果该语句仍然为真,则再次运行,直到该语句为假,因此您想要的是退出要求(假设玩家赢了……就用那个?)

示例

do {
    xc = false;
    if(points == condition){
        xc = true;
    }
    // some code
} while(!xc)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 2012-02-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多