第二个元素开始,先赋值,和前面的元素对比,如果没有重复的,就把该元素赋值给array1[i],

public class test1125 { public static void main(String[] args) { int array1[]=new int[7]; boolean flag=true; int count=0; array1[0]=(int) (1+Math.random()(30-1+1)); for(int i=1;i<array1.length;i++){ #给数组当前元素赋值一个随机数 array1[i]=(int) (1+Math.random()(30-1+1)); while(flag){ #判断刚赋值的随机数和前面的元素是否有相等的,如果有就重新赋值,并跳出当前循环 for(int j=0;j<i;j++){ if(array1[i]==array1[j]){ array1[i]=(int) (1+Math.random()*(30-1+1)); break; } #引入count变量,是为了如果对比了一遍没有相同的,当count==i时,说明已经验证了一遍没有相同的元素,当前元素赋值是可以的,flag=false,跳出当前while无限循环 count++; if(count==i){ flag=false; count=0; } } } flag=true; } for(int i=0;i<array1.length;i++){ System.out.print(array1[i]+"\t"); } } }