JAVA, 桌游。随机骰子数字不是随机的

JAVA, Board game. Random dice numbers not random

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

我有一个 class 可以在 1 和 6 之间创建一个随机数:

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

主要class:

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();
    }

}

谢谢!

得到随机结果的代码:

int roll = dice.throwDice();

只运行一次。您调用 throw 方法一次。您将结果而不是 "pointer" 存储到函数中,只要 roll 在某处被使用,该函数就会被重复调用。

所以你应该把那行:

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

就在你期待另一次掷骰子的地方前面!

将你的 Dice class 改成这个。

public class Dice {
    private Random random;
    public Dice(){
        random = new Random();
    }

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

并在循环内更新 roll = dice.throwDice();。 这将起作用,因为您的 Dice 现在有一个随机实例,每次调用 throwDice() 时都会生成新的随机整数。

int roll = dice.throwDice(); 添加到循环后,您可能会发现每次都获得相同的角色序列。如果您不希望这样,则必须设置随机种子。

看到这个问题:Java random numbers using a seed

public class Dice {
    private Random random;
    public Dice(){
        random = new Random();
    }

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

这会起作用,因为你的 Dice 现在有一个随机实例,每次调用 throwDice() 时都会生成新的随机整数