下面写了俩个方法,有问题指出来,有更简单的方法欢迎分享
- package TestDemo;
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.Random;
- /*
- * 生成10个随机数,保证不重复
- */
- public class TestDemo2 {
- public static void main(String[] args) {
- // 数组做法
- Random rdm1 = new Random();
- int[] intRet = new int[10];
- int intRd = 0;
- int count = 0;
- int flag = 0;
- while (count < intRet.length) {
- intRd = rdm1.nextInt(10);
- for (int x = 0; x < count; x++) {
- if (intRet[x] == intRd) {
- flag = 1;
- break;
- } else {
- flag = 0;
- }
- }
- if (flag == 0) {
- intRet[count] = intRd;
- count++;
- System.out.println(intRd);
- }
- }
- System.out.println("**************************");
- // 集合做法
- Collection<Integer> c = new ArrayList<Integer>();
- Random rdm2 = new Random();
- while (c.size() < 10) {
- int a = rdm2.nextInt(10);
- if (!c.contains(a)) {
- c.add(a);
- }
- }
- System.out.println("c:" + c);
- }
- }
复制代码
|
|