【问题标题】:Rolling dice a specific number of times Java掷骰子特定次数Java
【发布时间】:2016-12-15 22:46:13
【问题描述】:

我是 Java 新手,这是我必须做的:

如果玩家在 1 轮中 5 次在 2 个骰子上获得双六,则选择 10 到 30 之间的随机数。例如,如果该数字是 20,则其他两个骰子应掷 20 次,然后将这两个数字相乘并得到累积乘积。

这只是大计划的一小部分,这是我迄今为止所做的:

if (ninedice == 6 && sixdice == 6) {
    rolledDoubleSix++;
    if (rolledDoubleSix == 5) {
        dicerolls = (int) Math.ceil(Math.random() * (30 - 10 + 1) + 10);
        int ninediceproduct = dicerolls;
        int sixdiceproduct = dicerolls;
        if (ninediceproduct > 0) {
            ninediceproduct=(int)Math.ceil(Math.random() * 9);
        }
        if (sixdiceproduct > 0) {
            sixdiceproduct = dicerolls * (int) Math.ceil(Math.random() * 6);
        }
        int cumulativetotal = 0;
        int cumulative = sixdiceproduct * ninediceproduct;
        cumulativetotal = cumulativetotal + cumulative;
        accountpoints = accountpoints + cumulativetotal;
        accountptsoutput.setText("" + accountpoints);

我的问题是我不知道如何让两个骰子滚动特定的次数。如果 10 到 30 之间的随机数是 18,如何让这些骰子掷出 18 次?

【问题讨论】:

  • 你了解过“for循环”吗?
  • 不是很多。但这有什么帮助呢?
  • 嗯,“for 循环”可以让您一遍又一遍地重复某些内容。看来你可能想要一个在这里。所以我建议阅读 Oracle 提供的在线 Java 教程。

标签: java netbeans dice


【解决方案1】:

就像其他人所说的使用 for 循环。

另一种方法是拥有多个变量。也使用 java.util.Random(以及随后的 r.nextInt(seed) + 1 方法)而不是 Math.random。

我会这样做

Random r = new Random();
int firstSpin = r.nextInt(6) + 1; //+1 so result cannot be zero
int secondSpin = r.nextInt(6) + 1;
//more spins if needed
if(firstSpin == 6 && secondSpin == 6) {
//do something
}

【讨论】:

    【解决方案2】:

    好吧,我认为您正在寻找的东西称为循环。

    这是一个基本示例: https://docs.oracle.com/javase/tutorial/java/nutsandbolts/for.html

    它用于重复代码。

    【讨论】:

    • 欢迎来到 Stack Overflow!虽然这在理论上可以回答这个问题,it would be preferable 在此处包含答案的基本部分,并提供参考链接。
    • 我试过用这个:for(int roll=0; roll>=dicerolls; roll++) 其中 dicerolls 是 10 到 30 之间的随机数
    • @JohnSmith 这根本不会执行,因为 roll 永远不会大于或等于 diceroll(即 15-30)。您应该改用“roll
    • @JohnSmith roll < dicerolls,>= 未进入循环,因为初始条件为假。
    猜你喜欢
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 2015-12-09
    • 1970-01-01
    • 2011-04-27
    • 1970-01-01
    • 2018-12-17
    • 2018-09-08
    相关资源
    最近更新 更多