JAVA系列(11):产生指定范围的随机整数

以下三种方法进行产生随机整数。

1. java.lang.Math.random()

java.lang.Math.random() 方法的用法:

public static double random()

返回:一个大于等于0.0 且小于1.0的伪随机double类型的数。

如果需要返回符合在[min,max]范围的int型的整数:

int num = min + (int)(Math.random() * (max-min+1));

代码:

// import Math class in Java;
import java.lang.Math;

public class GenerateRandomNumber {
	public static void printArray(int[] arr) {
		for (int i=0; i<arr.length; i++) {
			System.out.println(arr[i]);
		}
	}
	public static void main(String[] args) {
		int min = 5;
		int max = 10;
		int[] arr = new int[10];
		for (int i=0; i<10; i++) {
			arr[i] = min + (int)(Math.random()*(max - min +1));
		}
		printArray(arr);
	}
}

效果:

8
10
9
8
10
7
6
7
5
8

2. java.util.Random

Random 是 java 提供的一个伪随机数生成器。

import java.util.Random;

/**
 * Returns a pseudo-random number between min and max, inclusive.
 * The difference between min and max can be at most
 * <code>Integer.MAX_VALUE - 1</code>.
 *
 * @param min Minimum value
 * @param max Maximum value.  Must be greater than min.
 * @return Integer between min and max, inclusive.
 * @see java.util.Random#nextInt(int)
 */
public static int randInt(int min, int max) {

    // NOTE: Usually this should be a field rather than a method
    // variable so that it is not re-seeded every call.
    Random rand = new Random();

    // nextInt is normally exclusive of the top value,
    // so add 1 to make it inclusive
    int randomNum = rand.nextInt((max - min) + 1) + min;

    return randomNum;
}

方法二和方法一类似,只不过一个是Math库中的,一个是util中的。

3. java.util.concurrent.ThreadLocalRandom

import java.util.concurrent.ThreadLocalRandom;

public class GenerateRandomNumber {
	public static void printArray(int[] arr) {
		for (int i=0; i<arr.length; i++) {
			System.out.println(arr[i]);
		}
	}
	public static void main(String[] args) {
		int min = 5;
		int max = 10;
		int[] arr = new int[10];
		for (int i=0; i<10; i++) {
			// nextInt is normally exclusive of the top value,
			// so add 1 to make it inclusive
			arr[i] = ThreadLocalRandom.current().nextInt(min, max + 1);
		}
		printArray(arr);
	}
}

效果:

8
9
9
10
6
8
10
7
5
8

参考:

  1. StackOverflow 产生随机整数

最近开通了个公众号,主要分享推荐系统,风控等算法相关的内容,感兴趣的伙伴可以关注下。
在这里插入图片描述
公众号相关的学习资料会上传到QQ群596506387,欢迎关注。

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

rosefunR

你的赞赏是我创作的动力!

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值