日期:2014-05-20 浏览次数:20716 次
import java.util.Random; public class Test { public static void main(String args[]) { int[] n = getRandomSeries(20); for(int a : n) { System.out.print(a + " "); } } public static int[] getRandomSeries(int size) { int[] series = new int[size]; for(int i = 0; i < size; i++) { series[i] = i + 1; } Random ran = new Random(); for(int i = 0, k = size * 2; i < k; i++) { int index1 = ran.nextInt(size); int tmp = series[index1]; int index2 = ran.nextInt(size); series[index1] = series[index2]; series[index2] = tmp; } return series; } }
------解决方案--------------------
List<Integer> list = new ArrayList<Integer>(); Random rnd = new Random(); for (int i = 0; i < 20; i++) { int j = rnd.nextInt(21); if (!list.contains(j) && j != 0) { list.add(j); } else { --i; } } Integer[] ii = list.toArray(new Integer[20]); Arrays.sort(ii); for (Integer i : ii) { System.out.println(i); }