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

java产生不重复的随机数,我的注释已写,求助?
/**
 * 1.实现数组元素的打乱,并生成一个新的数组
 * @author Administrator
 *
 */
public class QuestionOne {

/**
* @param args
*/
public static int[] temp = new int[10]; 
public static int[] result = new int[10];

public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc = new Scanner(System.in);
Random rand = new Random();

//循环为第一个数组赋值
for(int i = 0 ; i < temp.length; i++){
System.out.println("请输入第" + i+ "元素的值");
temp[i] = sc.nextInt();
}
System.out.print("排序前:");
System.out.print("排序后:");
//循环输出第一个数组
for(int i = 0 ; i < temp.length ; i++){
System.out.print(temp[i] + "\t");
}
System.out.println();
boolean y = true;
//外城循环控制输出的个数
while(y = true){
//产生一个长度为temp.length的随机数
int number = rand.nextInt(temp.length);
//内城循环查看有没重复出现的数
for(int i = 0 ; i < result.length ; i++){
//为result数组随机的第几个元素赋值
result[i] = temp[number];
//判断result数组中元素为0的元素, 如果为零 ,则result的这个元素没有被赋值,不为零时 ,被赋值
if(result[i] == 0 ){
break;
}else{
System.out.print(result[i] + "\t");
}
}
}
}
}

------解决方案--------------------
//外城循环控制输出的个数
while(y = true){
-----------------------
怎么是一个等号?
------解决方案--------------------
一种改法,供楼主参考
Java code

public class QuestionOne {

    public static int[] temp = new int[10];
    public static int[] result = new int[10];

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Scanner sc = new Scanner(System.in);
        Random rand = new Random();

        // 循环为第一个数组赋值
        for (int i = 0; i < temp.length; i++) {
            System.out.println("请输入第" + i + "元素的值");
            temp[i] = sc.nextInt();
        }
        System.out.print("排序前:");
        // 循环输出第一个数组
        for (int i = 0; i < temp.length; i++) {
            System.out.print(temp[i] + "\t");
        }
        System.out.println();
        System.out.print("排序后:");
        // 外城循环控制输出的个数
        for (int i = 0; i < result.length; i++) {
            // 产生一个长度为temp.length的随机数
            int number = rand.nextInt(temp.length);
            //若和以前的随机数重复则重新生成随机数直到新的不重复数字出现
            while (temp[number]==0) number = rand.nextInt(temp.length); 
            // 为result数组随机的第几个元素赋值
            result[i] = temp[number];
            temp[number] = 0; //做记号,表示此序号已经处理过,以后不能再使用此序号
            System.out.print(result[i] + "\t");
        }
    }
}