Java中随机数Random类和Math.random()方法的简介说明

戚薇 Java经验 发布时间:2023-06-24 14:53:31 阅读数:17425 1
下文笔者讲述随机数Random类和Math.random()方法的功能说明
学习完本篇之后,你将掌握Random类和Math.random()随机数方法分享,如下所示

Random类和Math.random()方法的简介

 Random类:
    new Random()可指定种子
    可获取随机int、long、double、boolean等值
    也可以指定范围[0,x) 

 Math.random()方法:
    获得[0,1)之间的随机double数
    不包括1
例:随机数Random类和Math.random()方法的示例
package testrandom;
 
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

public class TestRandom {
 
	public static void main(String[] args) throws Exception {
		RandomTest();
		System.out.println("==================================");
		Map<Integer,Integer> m = new HashMap<>();
		for(int i=0;i<1000000;i++) {
			int j = randomInt(5,10);
			if(m.containsKey(j)) {
				int v = m.get(j);
				m.put(j, ++v);
			}else {
				m.put(j, 1);
			}
		}
		System.out.println(m);
	}
 
	public static void RandomTest() {
		//Random对象的nextXXXX()方法获得各种随机值(int,long,double...)
		Random r = new Random();
		//r.nextInt();r.nextLong();r.nextDouble();...
		int a = r.nextInt();//随机正负int值
		System.out.println(a);
		//可以用Math的abs方法始终获得非负值
		System.out.println(Math.abs(a));
		int b = r.nextInt(10);//[0,10)随机int值
		System.out.println(b);
		//Math的静态random方法(实际使用的是Random对象的nextDouble方法,该Random是static final类型)
		double c = Math.random();//[0,1)随机double值
		System.out.println(c);
	}
	
	/**
	 * 获得a到b的随机整数(a<=b)
	 * @param a 起始值
	 * @param b 结束值
	 * @return 大于等于a,小于等于b的随机数
	 * @throws Exception a大于b异常
	 */
	public static int randomInt(int a,int b) throws Exception {
		if(a>b) {
			throw new Exception("error:a>b");
		}
		Random r = new Random();
		int x = r.nextInt(b-a+1);
		return x+a;
	}
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202306/16875896596878.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者