我的代码:
import java.util.*;
/**
* 生成一个100个数字以内无序数组,不重复
* @author 李晗
*
*/
public class lihan {
public static final int HOWMANY=100;
public static int fill(int[]kaka){
ArrayList al=new ArrayList();
for(int i=1;i<=HOWMANY;i++){
al.add(new Integer(i));
}
//生成无序的数组
for(int i=1;i<=HOWMANY-1;i++){
int pos=(int)(Math.random()*al.size());
kaka[i]=((Integer)al.get(pos)).intValue();
al.remove(pos);
}
kaka[HOWMANY]=-1;
return ((Integer)al.get(0)).intValue();
}
//打印出数组
public static void printArray(int[]a){
for(int i=1;i<a.length;i++){
System.out.print(a[i]+" ");
}
System.out.println();
}
public static void main(String[]args){
int []h=new int[HOWMANY+1];
fill(h);
printArray(h);
}
}
后来发现别人的不错,思路拿来,顺便改一下:
import java.util.*;
public class lihan {
public static void main(String[] args) {
int[] seed=new int[100];
for(int k=0;k<100;k++)
{
seed[k]=k;
}
int [] ranArr = new int [100];
Random ran = new Random();
for(int i = 0 ; i <seed.length ; i++){
int j = ran.nextInt(seed.length-i);
ranArr [i] = seed [j];
seed [j] = seed [seed.length-1-i];
System.out.print (ranArr[i]+" ");
}
}
}
打印结果:53 67 44 12 61 34 5 16 85 74 4 92 54 58 55 88 22 72 28 77 8 56 38 91 75 82 33 73 31 7 98 62 84 37 17 6 87 25 94 18 19 71 30 36 41 46 11 50 1 90 42 83 48 63 39 40 43 51 96 95 69 99 15 97 20 26 47 2 93 79 52 80 3 59 65 70 13 57 9 32 81 0 14 76 49 35 86 10 21 78 24 66 60 64 89 29 68 27 45 23
第二次执行:19 57 87 40 1 21 14 10 15 5 90 9 65 6 84 41 12 53 59 33 89 34 25 16 72 88 85 36 79 97 58 69 77 2 95 39 55 8 96 28 11 37 64 43 45 4 92 29 91 68 73 93 32 20 23 30 74 7 35 49 48 67 18 83 78 3 26 17 22 70 76 81 31 62 51 54 71 98 82 24 60 47 0 80 63 56 61 38 50 86 94 13 27 66 75 44 42 46 99
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/lihan6415151528/archive/2008/12/20/3562613.aspx