以下三种方法进行产生随机整数。
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
参考:
最近开通了个公众号,主要分享推荐系统,风控等算法相关的内容,感兴趣的伙伴可以关注下。
公众号相关的学习资料会上传到QQ群596506387,欢迎关注。