您的位置:首页 > 编程语言 > Java开发

JAVA产生指定范围的随机整数

2018-02-03 19:12 1071 查看

1、方法一Math.random()

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


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

}
}


因为使用了强制转换类型,所以是max-min+1

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、标准库

org.apache.commons.lang3.RandomUtils 提供了如下产生指定范围的随机数方法:

// 产生 start <= 随机数 < end 的随机整数
public static int nextInt(final int startInclusive, final int endExclusive);

// 产生 start <= 随机数 < end 的随机长整数
public static long nextLong(final long startInclusive, final long endExclusive);

// 产生 start <= 随机数 < end 的随机双精度数
public static double nextDouble(final double startInclusive, final double endInclusive);

// 产生 start <= 随机数 < end 的随机浮点数
public static float nextFloat(final float startInclusive, final float endInclusive);


参考:

1.GitHub 产生随机整数
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: