java中,我写了找随机数不重复的代码,但是找出的随机数有重复的,求大神知道

public class radom {

public static void main(String[] args) throws Exception{
final int L=10;
int[] a=new int[L];

for(int i=0;i<a.length;i++){

a[i]=(int)(Math.random()*(L));

for (int j = 0; j <i; j++) {

while(a[i]==a[j])
{
a[i]=(int)(Math.random()*(L));
}
}
System.out.println(a[i]);

}

}}

public class radom {

public static void main(String[] args) throws Exception{
final int L=10;
int[] a=new int[L];

for(int i=0;i<a.length;i++){

a[i]=(int)(Math.random()*(L));

for (int j = 0; j <i; j++) {

while(a[i]==a[j])
{
a[i]=(int)(Math.random()*(L));
j=0;//必须让j重新为0,因为a[i]已经重新取了随机数,有可能与0到j之 间的数重复,必须重新遍历以确保数字的唯一性。
}
}
System.out.println(a[i]);

}

}}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-08-28
你如果需要不重复的随机数,就需要用到时间戳,时间是永远不会重复的
第2个回答  2011-08-28
final int L = 10;
int[] a = new int[L];

for (int i = 0; i < a.length; i++) {

a[i] = (int) (Math.random() * (L));

int j = 0;
boolean isSame = false;
while(j < i) {

while (a[i] == a[j]) {
a[i] = (int) (Math.random() * (L));
isSame = true;
}
// 还要和前面的比较
if(isSame) {
j = 0;
isSame = false;
}
else j++;
}
System.out.println(a[i] + " ");

}
相似回答