首页 > 解决方案 > JAVA,棋盘游戏。随机骰子数字不是随机的

问题描述

我是 Java 新手并编写代码。我想编写一个简单的棋盘游戏。但是如果我掷骰子,我每次掷骰子都会得到相同的数字。我做错什么了?

我有一个类来创建 1 到 6 之间的随机数:

public class Dice {
    public int throwDice() {
        Random random = new Random();
        int dice = random.nextInt(6) + 1;
        return dice;
    }
}

主要课程:

public class BoardGame{

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        String r;
        Dice dice = new Dice();
        int roll = dice.throwDice();
        int position = 0;
        int finish = 40;

        while (finish >= position) {
            do {
                System.out.print("Roll the dice (r): ");
                r = input.nextLine();
            } while (!r.toLowerCase().equals("r"));

            if (r.toLowerCase().equals("r")) {
                System.out.println("You have rolled " + roll + ".");
                position += roll;
                System.out.println("You are now on square " + position + ".");
            }

        }
        System.out.println("You won!");
        input.close();
    }

}

谢谢!

标签: javarandomdice

解决方案


确实得到随机结果的代码:

int roll = dice.throwDice();

只运行一次。您调用一次throw 方法。roll您存储结果,而不是指向在某处使用时会重复调用的函数的“指针” 。

所以你应该把那行:

roll = dice.throwDice();
System.out.println("You have rolled " + roll + ".");

就在您期望再次掷骰子的地方的前面!


推荐阅读