快捷搜索: 王者荣耀 脱发

Java 生产随机数Math.random()方法的使用

公式:

Math.random()*(max-min)+min

生成大于等于min小于max的double型随机数;

例如:

定义一个随机1到5(取不到5)的变量 [1,5)

第一种方法:int number=(int)(Math.random()*(5-1)+1); 第二种方法:int number = (int)(Math.random()*4+1);

第三种方法:int number=(int)(Math.random()*10)//生成[0,9]之间的随机整数。

补充:

若想要生成不重复的随机数,可使用java中的Set数据结构默认元素不重复

//随机生成0——999999以内的不重复整数
public static void main(String args []){
	Set<Integer> set = new HashSet<Integer>();
	int times = 1000000;
	for(int i = 0 ;i<times;i++){
		int r = Math.random()*times;
		set.add(r);
	}
}

若要以当前时间为种子获取随机数

import  java.util.Random;
 
public  class  RandomDemo {
     public  static  void  main(String[] args) {
         long  t = System.currentTimeMillis(); //获得当前时间的毫秒数
         Random rd =  new  Random(t); //作为种子数传入到Random的构造器中
         System.out.println(rd.nextInt()); //生成随即整数
     }
}

//如果说要生成1到100以当前时间为种子的随机数,则传入一个范围参数就可以控制
System.out.println(rd.nextInt( 100 )); //生成随即整数 0~99包含0 也包含 99
System.out.println(rd.nextInt( 101 )); //生成随即整数 0~100包含0 也包含 100
经验分享 程序员 微信小程序 职场和发展