JavaDemo——随机数Random类和Math.random()方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/FlyLikeButterfly/article/details/82857374

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

2.Math.random()方法,获得[0,1)之间的随机double数,不包括1;

demo:

/**
 * 2018年9月20日下午4:00:02
 */
package testrandom;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

/**
 * @author XWF
 *
 */
public class TestRandom {

	/**
	 * @param args
	 * @throws Exception 
	 */
	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;
	}
}

结果:

猜你喜欢

转载自blog.csdn.net/FlyLikeButterfly/article/details/82857374