我有一个返回随机值的方法。
public int newRandom() {
Random random = new Random();
int o = random.nextInt(9 - 0 + 1) + 0;
return o;
}
在生成该值之后,我当前正在另一个函数内设置一个变量作为该函数的结果,我想要做的是让另一个类知道该变量具有相同的结果,我的意思是两者都具有相同的结果随机数,由于某种原因,我无法自行解决。实现这一目标的最佳方法是什么?
答案 0 :(得分:0)
你的意思是这样吗?
import java.util.Random;
public class A
{
public static Random random = new Random();
}
public class B
{
public int getRandomInt()
{
return A.random.nextInt();
}
}
答案 1 :(得分:0)
使用公共静态变量创建基类,并且当您从基类继承这些新类并创建新实例时,它们共享相同的变量:
dotnet new
答案 2 :(得分:0)
考虑使用组合,其中多个对象(可能是不同的类)共享提供随机值的类的相同实例。例如,给定此类以跟踪随机值:
private class RandomProvider {
private final Random random = new Random();
private int currentValue;
private int newRandom() {
currentValue = random.nextInt(10);
return currentValue;
}
private int getCurrentValue() {
return currentValue;
}
}
和另一个使用RandomProvider
的类:
private class A {
private final RandomProvider randomProvider;
private A(RandomProvider randomProvider) {
this.randomProvider = randomProvider;
}
private int getCurrentRandomValue() {
return randomProvider.getCurrentValue();
}
}
因此,A
(或某些其他类)的几个实例可以使用RandomProvider
的相同实例:
RandomProvider randomProvider = new RandomProvider();
System.out.println("new random value is " + randomProvider.newRandom());
A a1 = new A(randomProvider);
System.out.println("A1 sees current random value as " + a1.getCurrentRandomValue());
A a2 = new A(randomProvider);
System.out.println("A2 sees current random value as " + a2.getCurrentRandomValue());
randomProvider.newRandom();
System.out.println("A1 sees current random value as " + a1.getCurrentRandomValue());
System.out.println("A2 sees current random value as " + a2.getCurrentRandomValue());
示例输出:
new random value is 9
A1 sees current random value as 9
A2 sees current random value as 9
A1 sees current random value as 3
A2 sees current random value as 3