试图随机掷两个骰子并加上总和直到它达到二十

时间:2018-04-18 02:57:59

标签: java loops class methods main

我正在尝试编写一个程序,随机滚动两个骰子,将它们加在一起,并一直这样做,直到它达到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;

    }

}   

1 个答案:

答案 0 :(得分:0)

正如@KamalNayan所述,你需要循环rollingDice直到你处于或高于21,并且不需要将int agruments传递给rollingDice方法,因为滚动的die值是在该方法的范围内生成的。对某些内容的一些印刷也有助于展示运行期间发生的事情:

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