随机指定范围内N个不重复的数
randomCommon()方法负责制作赋值随机指定范围内N个不重复的数;
chachong()方法负责查重,判断数组中是否存在重复的数;
public class zuoye9_23_2 {
public static int[] randomCommon(int min,int max,int n)
{
int str[]=new int[n];
int i=0,j;
while(i<n){
int num=(int)(Math.random()*(max-min+1))+min;//分配一个随机数
for(j=0;j<n;j++) {
if(num==str[j]) {
num=(int)(Math.random()*(max-min+1)+min);//重新分配一个随机数
j=-1;//j重置为0
}
}
str[i]=num;
i++;
}
return str;
}
public static void main(String[] args)
{
int[] str=randomCommon(90,100,11);
for(int temp:str) {
System.out.print(temp+" ");
}
chachong(str);
}
public static void chachong(int[] a)
{
for(int i=0;i<a.length;i++) {
int count=-1;
for(int j=0;j<a.length;j++) {
if(a[i]==a[j]) {
count++;
}
if(count==1) {
System.out.println("\n查到重复的!!!"+a[i]);
break;
}
}
}
System.out.println("\n恭喜,数组中无重复的值");
}
}
输出
为了确保程序是否真正能行,范围需要小些,需要多运行几次,查看是否有重复值。