【发布时间】:2019-03-04 20:18:25
【问题描述】:
我是一名 Java 程序员新手,需要创建两个随机数。我们被指示使用 System.currentTimeMillis() 但是我不知道为什么我会得到这么多重复的数字。
import java.util.Random;
public class TestClass1 {
public static void main(String[] args) {
int points = 0;
while (points < 100) {
int[] scoreInfo = diceGen();
System.out.println(scoreInfo[0]);
System.out.println(scoreInfo[1]);
points += 1;
}
}
public static int[] diceGen() {
Random num = new Random(System.currentTimeMillis());
int dice1 = num.nextInt(6)+1;
int dice2 = num.nextInt(6)+1;
int[] numbers = {dice1, dice2};
return numbers;
}
}
输出: 6 6 6 6 6 6 6 6 6 6 6 6 6 6 4 2 4 2 4 2 4 2 4 2 4 2 4 2 4 2 4 2 4 2 4 2 4 2 4 2 4 2 4 2 3 4 3 4 3 4 3 4 3 4 3 4 3 4 3 4 3 4 3 4 3 4 3 4 3 4 3 4 1 4 1 4 1 4 1 4 1 4 1 4 1 4 1 4 1 4 1 4 1 4 1 4 1 4 1 4 1 4 1 4 1 4 1 4 2 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 2 6 5 6 5 6 5 6 5 6 5 6 5 6 5 6 5 6 5 6 5 6 5 6 5
【问题讨论】:
-
我们被指示使用 System.currentTimeMillis()... 你是如何被指示使用它的?也许你不应该这样使用它。
-
除非您需要可重复的结果,否则您不应该明确地播种
Random。你应该重用同一个实例。 -
播种一次并重复使用您的
Random实例。
标签: java