淺析Java隨機(jī)數(shù)與定時(shí)器
產(chǎn)生90-100的重復(fù)的隨機(jī)數(shù):
public class RandomTest {
public static void main(String[] args){
/*
* Math.random()方法默認(rèn)double類型,所以需要強(qiáng)制轉(zhuǎn)換為int
*/
int x=(int)(Math.random()*(100-90+1)+90); //(max-min+1)+min=min-max
System.out.println(x);
}
}
產(chǎn)生90-100不重復(fù)的隨機(jī)數(shù):
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; //隨機(jī)數(shù)個(gè)數(shù)
Random random = new Random();
Set<Integer> set=new HashSet<>(); //hashset容器中只能存儲(chǔ)不重復(fù)的對(duì)象
while(set.size()<count){ //hashset儲(chǔ)存的元素?cái)?shù)目
int x = random.nextInt(max-min+1)+min; //產(chǎn)生隨機(jī)數(shù)
set.add(x); //把隨機(jī)數(shù)添加到hashset容器中
}
for(int i:set){ //foreach遍歷容器元素
System.out.println(i);
}
}
}
每一秒產(chǎn)生90-100的重復(fù)的隨機(jī)數(shù):
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
public class RandomTest {
void timer(){
Timer timer = new Timer(); //創(chuàng)建定時(shí)對(duì)象
timer.schedule(new TimerTask() {
public void run() { //TimerTask實(shí)現(xiàn) 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表示無(wú)延遲,1000ms=1s
}
public static void main(String[] args){
RandomTest ran=new RandomTest();
ran.timer(); //調(diào)用定時(shí)任務(wù)
}
}
本文轉(zhuǎn)載于:https://www.idaobin.com/archives/301.html
相關(guān)文章
SpringCloud?中防止繞過(guò)網(wǎng)關(guān)請(qǐng)求直接訪問后端服務(wù)的解決方法
Java int與integer的對(duì)比區(qū)別
Spring中的ApplicationContext與BeanFactory詳解
Java中StringBuilder類常用方法總結(jié)
SpringBoot整合WebService的實(shí)現(xiàn)示例
詳解Java在redis中進(jìn)行對(duì)象的緩存
JAVA多線程與并發(fā)學(xué)習(xí)總結(jié)分析

