gpt4 book ai didi

java - 随机发生器自动随机

转载 作者:行者123 更新时间:2023-12-01 11:11:11 25 4
gpt4 key购买 nike

我们知道下面的代码是随机数

Random generator = new Random();
number = generator.nextInt(VALUE) + 1;

如果单击按钮,我会将这段代码添加到随机生成器

button1 = (Button)findViewById(R.id.buttonblack);
if(v==button1) {

// Here, we are generating a random number
Random generator = new Random();
number = generator.nextInt(5) + 1;
// The '5' is the number of values

// Here, we are checking to see what the output of the random was
switch(number) {

case 1: if(bla.. bla.. bla.. == 1){
//Do some blaa. blaa. blaa. logic
}
else if(bla.. bla.. bla.. == 2){
//Do some blaa. blaa. blaa. logic
}
break;
//and so on..

我的问题是如何使随机生成器方法每 2 秒自动随机一次,然后越来越快,而不是通过单击按钮

以及如何在单击某个按钮时随机停止,例如

buttonstop = (Button)findViewById(R.id.buttonstop);    
buttonstop.setOnClickListener(new View.OnClickListener() {

public void onClick(View v){

//Stop Random generator

}
});

有人可以回答吗?谢谢

最佳答案

使用它,从 2 秒开始加快 20 毫秒

  private Handler mHandler = new Handler();
int ms=2000; //2secs.
Define a Runnable:

private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
// get random number here

// You could do this call if you wanted it to be periodic:

ms=ms-20; //20ms faster
mHandler.postDelayed(this, ms);

}
};

mHandler.postDelayed(mUpdateTimeTask, 100);

关于java - 随机发生器自动随机,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32351575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com