随机生成n个不相等的整数
package day0601_作业;
import java.util.Random;
public class Test2随机生成n个不相等的整数 {
public static void main(String[] args) {
int n = 6;//需要整数数量(n必须小于等于k)
int k = 100;//整数随机的取值范围
Random rand = new Random();//新建一个随机类
boolean[] bool = new boolean[k+1];
int randInt = 0;
for(int i = 0; i < n ; i++) {
do {
randInt = 1+rand.nextInt(k);//产生一个随机数
}while(bool[randInt]);
bool[randInt] = true;
System.out.print(randInt+",");
}
}
}
方法2
private static int[] random(int t,int k) {//t//数组长度 k //整数随机的取值范围,n必须小于等于k
int[] a = new int[t];
int n;
boolean flag;
for (int i = 0; i < a.length; i++) {
do {
flag = false;
n = 1 + new Random().nextInt(k);
for (int j = 0; j <= i; j++) {
if (n == a[j]) {
flag = true;
break;
}
}
} while (flag);
a[i] = n;
}
return a;
}