我正在尝试为我编写一个玩骰子游戏(普通 6 面骰子)的短程序。第一卷的数字被添加到分数中。第一次掷出后,如果我掷出 6,则游戏停止并记录分数(不加 6)。如果第一次掷出 6,那很好,它可以像任何其他数字 1 到 5 一样添加。我正在尝试运行这个游戏的一系列迭代,这样我就有一长串的得分前半身像(a胸围是滚动的 6)。我将这些分数重新排列为从小到大的顺序,然后找到列表的中位数,这是最佳停止的分数。
出于某种原因,我在运行程序时一直得到 13,但我知道答案应该是 15。在 Java 中使用 Random 会对中位数产生某种影响吗?我不完全知道 Random 如何生成数字以及它是否以平等的机会创造它们。此外,是否有任何不应该工作的东西突然弹出?
import java.util.*;
public class DiceRoller {
private static Random r = new Random();
private static final int games = 10001;
private static int[] totalScores = new int[games];
private static int index = 0;
public static void main(String[] args) {
int score = 0; boolean firstRoll = true;
while (index < games) {
int roll = roll();
if (firstRoll) {
score += roll;
firstRoll = false;
} else {
if (roll == 6) {
totalScores[index] = score;
index++;
score = 0; firstRoll = true;
} else {
score += roll;
}
}
}
System.out.println("The median is " + median() + ".");
}
public static int roll() {
return r.nextInt(6) + 1;
}
public static int median() {
Arrays.sort(totalScores);
int temp = totalScores[games / 2];
return temp;
}
}