我是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();
}
}
谢谢!
获得随机结果的代码:
int roll = dice.throwDice();
运行一次。你调用throw方法一次。你存储结果,而不是一个“指针”到一个函数,当roll
在某处使用时,它会被重复调用。
所以你应该把那一行:
roll = dice.throwDice();
System.out.println("You have rolled " + roll + ".");
就在你期待另一卷骰子的地方前面!
public class Dice {
private Random random;
public Dice(){
random = new Random();
}
public int throwDice(){
int dice = random.nextInt(6) + 1;
return dice;
}
}
这将起作用,因为您的Dice现在有一个随机实例,每次调用throwDice()时都会生成新的随机整数
将int roll = dice.throwDice();
添加到循环后,您可能会发现每次都获得相同的角色序列。如果您不想要,则必须设置随机种子。
将您的Dice类更改为此。
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();
。这将起作用,因为你的骰子现在有一个随机实例,每次调用throwDice()
时都会生成新的随机整数。