本问题已经有最佳答案,请猛点这里访问。
我是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实例。
Random()构造函数的参数是随机数生成器的种子。每次使用相同的种子创建一个新的Random实例时,它将生成相同的数字。由于diceGen()的执行时间不到一毫秒,因此您将创建具有相同毫秒数的多个实例。
相反,您需要创建单个Random实例并将其存储在字段中或将其作为参数传递。
代码执行得足够快,以至于在循环的两次迭代之间,System.currentTimeMillis()返回的值保持不变。因此,这些Random实例使用相同的种子创建并返回相同的值。
考虑使用System.nanoTime()或构造一个Random实例,并在所有迭代中重用它。
就像是
public static void main(String[] args) {
int points = 0;
Random num = new Random(System.nanoTime());
while (points < 100) {
int[] scoreInfo = diceGen(num);
System.out.println(scoreInfo[0] +"," + scoreInfo[1]);
points += 1;
}
}
public static int[] diceGen(Random num) {
int dice1 = num.nextInt(6) + 1;
int dice2 = num.nextInt(6) + 1;
int[] numbers = { dice1, dice2 };
return numbers;
}
是的,解决方法是不要搅动使用相同种子创建rng-做单身rng-因为每个后续调用都会返回一个新数字。
@Micromuncher当然可以,已编辑。
使rng成为全局范围。每次通话都会更改号码。如果您在每次调用生成器时为rng播种,则很有可能您将在相同的滴答声中调用种子,因此得到相同的编号。
import java.util.Random;
public class TestClass1 {
static public Random num = new Random(System.currentTimeMillis());
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() {
int dice1 = num.nextInt(6)+1;
int dice2 = num.nextInt(6)+1;
int[] numbers = {dice1, dice2};
return numbers;
}
}
rngs的工作方式是x = trunc( old_x * big_prime ) + prime,在第一次调用时,old_x是种子。
请考虑为您的解决方案提供解释,以帮助OP了解问题