一个用于生成随机数的类
具体用法:
1 2 3 4 5 6 7 8 9 10 |
//创建随机数对象 Random random = new Random();
//随机产生一个int类型取值范围内的数字。 int num1 = random.nextInt(); System.out.println(num1);
//产生一个[0-100]之间的随机数 int num2 = random.nextInt( 101 ); System.out.println(num2); //不包括101 |
写一个不含重复数字的随机数组
第一种:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
int [] num = new int [ 5 ]; boolean flag = true ; Random random = new Random(); for ( int i = 0 ; i < num.length; i++) { int a = random.nextInt( 5 ); for ( int j = i - 1 ; j >= 0 ; j--) { //当i == 0 的时候这一步不执行 if (a == num[j]) { flag = false ; } } if (flag) { num[i] = a; } else { i--; flag = true ; } } System.out.println(Arrays.toString(num)); |
第一种方法的改进:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public static void main(String[] args) { int [] num = new int [ 5 ]; Random random = new Random();
int index = 0 ; while (index < num.length) { int a = random.nextInt( 5 ); if (contains(num, index, a)) { //把判断有没有变成了一个方法 num[index++] = a; } } System.out.println(Arrays.toString(num)); }
public static boolean contains( int [] a, int index, int temp) { for ( int i = index - 1 ; i >= 0 ; i--) { if (temp == a[i]) { return false ; } } return true ; } |
第二种:
不推荐这种方法,虽然使用了 Arrays 自带的方法 ,但是这个方法的除最后一个元素以外的元素都是排好序的
这种随机有点不严谨
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
public static void main(String[] args) { int [] a = new int [ 5 ]; Random random = new Random(); int index = - 1 ; while (index < a.length - 1 ){ int b = random.nextInt( 5 ); if (contains(a,b,index)){ a[++index] = b; } } System.out.println(Arrays.toString(a)); } public static boolean contains( int [] a , int b , int index){ if (index < 0 ){ return true ; } Arrays.sort(a, 0 ,index + 1 ); //下标为[0,index+1)的数组排序 不包含index+1 return Arrays.binarySearch(a, 0 ,index + 1 ,b) < 0 ; //二分法查找下标为[0,index+1)范围内是否包含b } |
到此这篇关于Java中的随机数Random的文章就介绍到这了,更多相关随机数Random内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
原文链接:https://blog.csdn.net/qq_43856453/article/details/107983926