不写:
Random randomGenerator = new Random();
for (int idx = 5; idx <= 15; ++idx){
int randomInt = randomGenerator.nextInt(1);
每次我在函数中需要一个随机数时,是否可以将随机数生成器类的结果传递或调用到函数中?
例如,我有一个特殊的函数,它从另一个类接收变量
favoriteTracks(String fromExampleClass1, String fromExampleClass1again)
我能做吗
favoriteTracks(String fromExampleClass1, String fromExampleClass1again, Long fromRNGclass)
澄清:我的一个函数"favoriteTracks"需要从"ExampleClass1"传递的变量。同时,我希望它接收一个随机数作为变量(或者调用它,以最简单的为准)。在另一类中生成
public static long randomNum(){
Random randomGenerator = new Random();
for (int idx = 5; idx <= 15; ++idx){
int randomInt = randomGenerator.nextInt(1);
最简单的方法是将您想要的行为封装在一个单例中:
public class MyRandom {
public static final MyRandom myRandom = new MyRandom();
private Random randomGenerator = new Random();
public int makeRandom() {
// put your for loop here if you want, but it is not necessary
return 5 + randomGenerator.nextInt(11);
}
}
在其他地方。。。
x = MyRandom.myRandom.makeRandom();
这看起来像是你正在尝试做的事情的一个可能的解决方案。