浅析Java随机数与定时器

时间:2021-08-30 14:47:47

产生90-100的重复的随机数

?
1
2
3
4
5
6
7
8
9
public class RandomTest {
 public static void main(String[] args){
    /*
     * Math.random()方法默认double类型,所以需要强制转换为int
     */
 int x=(int)(Math.random()*(100-90+1)+90); //(max-min+1)+min=min-max
 System.out.println(x);
 }
}

产生90-100不重复的随机数:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import java.util.HashSet;
import java.util.Random;
import java.util.Set;
 
public class RandomTest {
    public static void main(String args[]){
        int max=100; //最大值
        int min=90; //最小值
        int count=max-min; //随机数个数
        Random random = new Random();
        Set<Integer> set=new HashSet<>(); //hashset容器中只能存储不重复的对象
        while(set.size()<count){ //hashset储存的元素数目
             int x = random.nextInt(max-min+1)+min; //产生随机数
             set.add(x); //把随机数添加到hashset容器中
        }
        for(int i:set){ //foreach遍历容器元素
            System.out.println(i);
        }
    }
}

每一秒产生90-100的重复的随机数:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
 
public class RandomTest {
     void timer(){
        Timer timer = new Timer(); //创建定时对象
        timer.schedule(new TimerTask() {
            public void run() { //TimerTask实现 Runnable接口的run方法
                 Random random = new Random();
                 int x = random.nextInt(100-90+1)+90; //(max-min+1)+min=min至max
//               int x=random.nextInt(100)%(100-90+1) + 90; //同样的效果
                 System.out.println(x);
            }
            
        },0,1000); //0表示无延迟,1000ms=1s
    }
 public static void main(String[] args){
    RandomTest ran=new RandomTest();
    ran.timer(); //调用定时任务
 }
}

本文转载于:https://www.idaobin.com/archives/301.html