随机数生成
数生成有很多种方法,暂且介绍以下2种
- Math类
- Random类
具体实现如下:
public static void main(String[] args) {
System.out.println("Math生成随机数:");
System.out.println("[0,1) ,double类型随机数" + Math.random());
int num = (int) (Math.random() * 10);
System.out.println("[0,10) ,int类型随机数" + num);
System.out.println("Random生成随机数");
Random random = new Random(10);
for (int i = 0; i < 5; i++) {
System.out.println(random.nextInt());
}
System.out.println("---");
// 直接使用Random无法避免生成重复的数字,如果需要生成不重复的随机数序列,需要借助数组和集合类
ArrayList list = new Demo_1().getDiffNO(10);
System.out.println("产生的n个不同的随机数:" + list);
}
/**
* 生成n个不同的随机数,且随机数区间为[0,10)
*
* @param n
* @return
*/
public ArrayList getDiffNO(int n) {
// 生成 [0-n) 个不重复的随机数
// list 用来保存这些随机数
ArrayList list = new ArrayList();
Random rand = new Random();
boolean[] bool = new boolean[n];
int num = 0;
for (int i = 0; i < n; i++) {
do {
// 如果产生的数相同继续循环,不添加进集合
num = rand.nextInt(n);
} while (bool[num]);
bool[num] = true;
list.add(num);
}
return list;
}
打印:
Math生成随机数:
[0,1) ,double类型随机数0.8433764926276198
[0,10) ,int类型随机数8
Random生成随机数
-1157793070
1913984760
1107254586
1773446580
254270492
---
产生的n个不同的随机数:[1, 9, 7, 3, 2, 0, 4, 6, 8, 5]```