日期:2014-05-20  浏览次数:20676 次

要求随机产生10个数,并放入到数组。要求,数组里的元素不能重复。请各位高手帮我看下思路一遍帮我解决下问题,谢谢了!
public class QuestionFour {

/**
* @param args
*/
//定义一个长度为10的静态数组;
public static int[] temp = new int[10];
public static void main(String[] args) {
//定义一个RANDOM对象
Random rand = new Random();
//外层循环为数组赋随机值
for(int i = 0 ; i < temp.length ; i++){
//产生一个10的随机数
int number = rand.nextInt(10);
//为数组赋值
temp[i] = number;
//循环数组的每个元素
for(int j = 1 ; j<=i ; j++){
//从数组的第一个元素开始,循环到数组长度为J的时候,如果有重复的值,则重新获得随机数,并把随机数赋值给temp数组
if(temp[i] == temp[j]){
number = rand.nextInt(10);
temp[j] = number;
//如果没有重复的数,则打印
}else{
System.out.print(temp[i]);
break;
}
}

}
}
}

------解决方案--------------------
Java code

final int len = 10;
Random rand = new Random();
int[] array = new int[len];
for(int i=0;i<len;i++){//遍历数组,填写随机数。
  int r = rand.nextInt(len);
  boolean old = false;//声明是否重复的标示符,重复时值为真。
  do{//循环检查新生成的随机数,直到它真的不是重复的为止
     old = false;//假设填写的随机数不是重复的
    for(j=0;j<i;j++){//遍历以前生成的数字,看有没有与当前重复的
      if(array[j]==r){
        old=true;//设置当前数,是重复的。
        r = rand.nextInt(len);//重新获取新随机数。
        break;
      }
    }
  }while(old);
  array[i] = r;//为数组添加新元素
}