这个问题已经有了最佳答案,请迅速访问这里。
我是Java的初学者,需要创建两个随机数。 我们被指示使用System.currentTimeMillis (),但我不知道为什么会得到这么重复的数字。
import java.util.Random;
公共类测试类1 {
publicstaticvoidmain (字符串[ ] args ) {
int points=0;
while(points100 ) {
int[] scoreInfo=diceGen (;
system.out.println (score info [0];
system.out.println (score info [1];
points =1;
}
}
公共静态int [ ] dice gen
random num=new random (system.current time millis ();
intdice1=num.nextint(6) 1;
intdice2=num.nextint(6) 1;
int[] numbers={dice1,dice2};
返回编号;
}
}
输出:
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
个
4
个
4
个
4
个
4
个
4
个
4
个
4
个
4
个
4
个
4
个
4
个
4
个
4
个
4
个
4
个
4
个
4
个
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 ) )的运行时间小于1毫秒,因此创建相同毫秒数的多个实例。
相反,必须创建单个Random实例,并将其存储在字段中或作为参数传递。
System.currentTimeMillis ) )返回的代码运行得足够快,以防止循环迭代之间的值发生变化。 因此,这些Random实例是使用相同的种子创建的,并返回相同的值。
请考虑使用System.nanoTime (),或构建Random实例以在所有迭代中重用。
就像这样
publicstaticvoidmain (字符串[ ] args ) {
int points=0;
random num=new random (system.nano time ();
while(points100 ) {
int[]scoreinfo=dicegen(num;
system.out.println (score info [0]、' scoreInfo[1];
points =1;
}
}
公共静态int [ ] dice gen (随机编号) {
intdice1=num.nextint(6) 1;
intdice2=num.nextint(6) 1;
int[] numbers={ dice1,dice2 };
返回编号;
}
是的,解决方法是不干扰使用同一种子创建RNG——打单身RNG——因为每次后续调用都会返回新数字。
@Micromuncher当然可以。 已编辑。
将rng纳入全球范围。 每次通话都更改号码。 如果每次调用生成器时都使用rng种子,则很可能会以相同的滴答声调用种子,并且编号相同。
import java.util.Random;
公共类测试类1 {
staticpublicrandomnum=new random (system.current time millis ();
publicstaticvoidmain (字符串[ ] args ) {
int points=0;
while(points100 ) {
int[] scoreInfo=diceGen (;
system.out.println (score info [0];
system.out.println (score info [1];
points =1;
}
}
公共静态int [ ] dice gen
intdice1=num.nextint(6) 1;
intdice2=num.nextint(6) 1;
int[] numbers={dice1,dice2};
返回编号;
}
}
rgs的工作方式是x=trunc(old_x*big_prime ) prime,在第一次调用中,old_x是种子。
请考虑解决方案说明,以帮助操作系统理解问题