尝试随机掷两个骰子并将总和相加直到达到 21

Posted

技术标签:

【中文标题】尝试随机掷两个骰子并将总和相加直到达到 21【英文标题】:Attempting to roll two dice randomly and add the sums till it reaches twentyone 【发布时间】:2018-09-28 03:34:27 【问题描述】:

我正在尝试编写一个程序,该程序随机掷两个骰子,将它们加在一起,并一直这样做,直到达到 21。如果达到 21,则获胜,但如果超过 21,则失败。

这是我到目前为止所拥有的,如果我能在如何正确掷骰子方面获得一些帮助,那就太好了。我是 java 初学者,所以仍在尝试理解语法。

import java.util.Random; 
public class TwentyOne

    public static void main(String[] args) 

        int dice1;
        int dice2;

        welcome();
        rollingDice(int dice1,int dice2);


    

    public static void welcome() 
        System.out.println("Welcome to the game of Twenty-One! FEELING LUCKY?! goodluck!");

    

    public static int rollingDice(int dice1, int dice2) 

        dice1 = (int)(Math.random()*6 + 1);
        dice2 = (int)(Math.random()*6 + 1);
        int sum = dice1 + dice2;
        return sum;

    

   

【问题讨论】:

在 while 循环中调用 rollingDice 方法,根据您的要求使用终止条件。此外,不需要传递参数,因为您是在方法本身中生成的 @KamalNayan 这也是我更改的内容,我收到错误提示我需要在方法中的每个参数后添加分号 【参考方案1】:

正如@KamalNayan 上面所说,您需要循环 rollingDice 直到您达到或超过 21 岁,并且不需要将 int 参数传递给 rollingDice 方法,因为滚动骰子值是在该方法的范围内生成的。打印一些正在发生的事情也有助于展示运行时发生的事情:

public static void main(String[] args) 

    welcome();

    int total = 0;
    while (total < 21) 
        total += rollingDice();
    ;
    System.out.println("Total for all rolls was: " + total);

    if (total == 21) 
        System.out.println("You win!");
    
    else 
        System.out.println("You lose.");
    



public static void welcome() 
    System.out.println("Welcome to the game of Twenty-One! FEELING LUCKY?! goodluck!");



public static int rollingDice() 

    int dice1 = (int) (Math.random() * 6 + 1);
    int dice2 = (int) (Math.random() * 6 + 1);
    int sum = dice1 + dice2;

    System.out.println(String.format("dice1: %d dice2: %d for a total: %d", dice1, dice2, sum ));

    return sum;


这里是获胜游戏的输出:

Welcome to the game of Twenty-One! FEELING LUCKY?! goodluck!
dice1: 4 dice2: 1 for a total: 5
dice1: 1 dice2: 4 for a total: 5
dice1: 1 dice2: 3 for a total: 4
dice1: 6 dice2: 1 for a total: 7
Total for all rolls was: 21
You win!

进程以退出代码 0 结束

【讨论】:

我不喜欢给出源代码,所以只是给出提示,让他自己尝试,新手的好习惯! :)

以上是关于尝试随机掷两个骰子并将总和相加直到达到 21的主要内容,如果未能解决你的问题,请参考以下文章

如何在Unity 3D中掷骰子

python使用pygal模拟掷骰子模拟1000次可是结果相加不是1000,求大神解答

LeetCode 1223. 掷骰子模拟 Dice Roll Simulation - Java - DP

python 由用户输入掷多少次骰子,然后统计每个面出现的次数

python之pygal:掷两个不同的骰子并统计大小出现次数

-------用Python编写骰子游戏-------几乎完成,但是有不明白的地方……