调用这个Math.Random()函数可以返回带正号的double值,该值大于等于0.0且小于1.0,即取值范围是[0.0,1.0)的左闭右开区间,返回值是一个伪随机选择的数,在该范围内(近似)均匀分布。例子以下:java
// 案例1 System.out.println("Math.random()=" + Math.random());// 结果是个double类型的值,区间为[0.0,1.0) int num = (int) (Math.random() * 3); // 注意不要写成(int)Math.random()*3,这个结果为0,由于先执行了强制转换 System.out.println("num=" + num);
下面Random()的两种构造方法:
Random():建立一个新的随机数生成器。
Random(long seed):使用单个 long 种子建立一个新的随机数生成器。算法
须要说明的是:你在建立一个Random对象的时候能够给定任意一个合法的种子数,种子数只是随机算法的起源数字,和生成的随机数的区间没有任何关系。以下面的Java代码:数组
Random rand =new Random(25); int i; i=rand.nextInt(100);
初始化时25并无起直接做用(注意:不是没有起做用),rand.nextInt(100);中的100是随机数的上限,产生的随机数为0-100的整数,不包括100。dom
具体用法以下例:函数
package com.yjj.random; import java.util.ArrayList; import java.util.Random; /** * @Description: * @Author: yinjunjie * @CreateDate: 2018/9/6 10:58 * @Version: 1.0 */ public class TestRandom2 { public static void main(String[] args) { // 案例2 // 对于种子相同的Random对象,生成的随机数序列是同样的。 Random ran1 = new Random(8); System.out.println("使用种子为8的Random对象生成[0,10)内随机整数序列: "); for (int i = 0; i < 10; i++) { System.out.print(ran1.nextInt(10) + " "); } System.out.println(); Random ran2 = new Random(8); System.out.println("使用另外一个种子为8的Random对象生成[0,10)内随机整数序列: "); for (int i = 0; i < 10; i++) { System.out.print(ran2.nextInt(10) + " "); } /** * 输出结果为: * * 使用种子为8的Random对象生成[0,10)内随机整数序列: * 4 6 0 1 2 8 1 1 3 0 * 使用另外一个种子为8的Random对象生成[0,10)内随机整数序列: * 4 6 0 1 2 8 1 1 3 0 * */ // 案例3 // 在没带参数构造函数生成的Random对象的种子缺省是当前系统时间的毫秒数。 Random r3 = new Random(); System.out.println(); System.out.println("使用种子缺省是当前系统时间的毫秒数的Random对象生成[0,10)内随机整数序列"); for (int i = 0; i < 10; i++) { System.out.print(r3.nextInt(10)+" "); } /** * 输出结果为: * * 使用种子缺省是当前系统时间的毫秒数的Random对象生成[0,10)内随机整数序列 * 1 6 7 6 7 4 3 7 8 3 * */ // 另外,直接使用Random没法避免生成重复的数字,若是须要生成不重复的随机数序列,须要借助数组和集合类 ArrayList list=new TestRandom2().getDiffNO(10); System.out.println(); System.out.println("产生的n个不一样的随机数:"+list); } /** * 生成n个不一样的随机数,且随机数区间为[0,10) * @param n * @return */ public ArrayList getDiffNO(int n){ // 生成 [0-n) 个不重复的随机数 // list 用来保存这些随机数 ArrayList list = new ArrayList(); Random rand = new Random(); boolean[] bool = new boolean[n]; int num = 0; for (int i = 0; i < n; i++) { do { // 若是产生的数相同继续循环 num = rand.nextInt(n); } while (bool[num]); bool[num] = true; list.add(num); } return list; } }
备注:下面是Java.util.Random()方法摘要:spa
下面给几个例子:
生成[0,1.0)区间的小数:double d1 = r.nextDouble();
生成[0,5.0)区间的小数:double d2 = r.nextDouble() * 5;
生成[1,2.5)区间的小数:double d3 = r.nextDouble() * 1.5 + 1;
生成-231到231-1之间的整数:int n = r.nextInt();
生成[0,10)区间的整数:
int n2 = r.nextInt(10);//方法一
n2 = Math.abs(r.nextInt() % 10);//方法二code
今天看到这篇博客,以为挺好的,分享一下, 下面是做者
做者:殷俊杰
连接:https://www.jianshu.com/p/ba2904cf4ea3对象