在java中人们可以输入随机数:
import java.util.Random;
我正在开发一款游戏,它对我游戏中的随机发生器至关重要。但它改变数字对我来说很快,我真的很喜欢它变成一个新的随机数字的时间。我怎么做?我试图在谷歌上搜索,但什么也没给我。
I think perhaps you've misunderstood how it works. When you call, for example, random.nextInt(10);
it returns a different number every time you call it. It is not 'always changing', it generates a sequence of numbers, and you are in control of when it does this. It will not generate new numbers until you ask it to.
You can assign it to a variable if you want to save it between calls to nextInt()
, etc.
谷歌什么都没给你?我对此表示高度怀疑。
public class Game {
private Random random = new Random(System.currentTimeMillis());
// Generate all the random numbers you need.
}
如果您按计划需要它们,请使用 aTimer
仅在闹钟响起时拨打下一个号码。
您可以使用Timer
andTimerTask
定期生成随机数,如下所示:
public class MyRandomNumberGenerator extends TimerTask{
int ramdomNumber =0;
Random r = new Random();
@Override
public void run() {
// TODO Auto-generated method stub
randomNumber = r.nextInt(10);
//Returns a pseudorandom, uniformly distributed int value between 0 (inclusive) and the specified value (exclusive) here it is 10,
}
public int getRandomNumber(){
return randomNumber;
}
}
现在在你想使用随机数的主类中
使用此代码
MyRandomNumberGenerator rng = new MyRandomNUmberGenerator();
Timer t = new Timer();
t.schedule(rng,System.getCurrentTimeMillis,10000);
int r = rng.getRandomNumber();
这里System.getCurrentTimeMillis
的意思是从现在开始计时器,10000
意味着每10000
毫秒都会创建一个新的随机数并将其存储在实例变量中,然后您可以使用类的getRandomNumber
方法访问该随机数MyRandomNumberGenerator
。
Random
每次调用对象的方法都会返回一个新的随机数。如果这不是您想要的,那么编写您自己的包含 的实例的类Random
,并检查您上次调用它以获得新随机数的时间。如果是时候换一个新的,请返回一个新的。像这样的东西:
class TimedRandom {
private final Random random = new Random();
private int lastNumber;
private long lastRefreshTime;
public int getNumber() {
long now = System.currentTimeMillis();
// If it's more than 2 seconds ago, generate a new random number
if (now - lastRefreshTime > 2000L) {
lastNumber = random.nextInt();
}
lastRefreshTime = now;
return lastNumber;
}
}
public static void main(String[] args) throws Exception {
Random random = new Random(System.currentTimeMillis());
for (int i = 0; i < 10; i++) {
int number = random.nextInt(10);
System.out.println("number: " + number);
// sleep 1s every generation
TimeUnit.SECONDS.sleep(1);
}
}