当我设置种子时,Java random 总是返回相同的数字? [英] Java random always returns the same number when I set the seed?
本文介绍了当我设置种子时,Java random 总是返回相同的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要有关我正在创建的随机数生成器的帮助.我的代码如下(在一个叫做 numbers 的类中):
I require help with a random number generator I am creating. My code is as follows (inside a class called numbers):
public int random(int i){
Random randnum = new Random();
randnum.setSeed(123456789);
return randnum.nextInt(i);
}
当我从另一个类调用这个方法时(为了生成一个随机数),它总是返回相同的数字.例如,如果我要这样做:
When I call this method from another class (in order to generate a random number), it always returns the same number. For example if I were to do:
System.out.println(numbers.random(10));
System.out.print(numbers.random(10));
它总是打印相同的数字,例如5 5. 我该怎么做才能打印两个不同的数字,例如5 8
it always prints the same number e.g. 5 5. What do I have to do so that it prints two different numbers e.g. 5 8
我必须设置种子.
谢谢
推荐答案
你需要在全班共享 Random()
实例:
You need to share the Random()
instance across the whole class:
public class Numbers {
Random randnum;
public Numbers() {
randnum = new Random();
randnum.setSeed(123456789);
}
public int random(int i){
return randnum.nextInt(i);
}
}
这篇关于当我设置种子时,Java random 总是返回相同的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文