生成指定范围不重复的随机数

题目:生成1-10范围中任意5个随机数。

方法一:不使用容器

 1 package com.study.pratice03;
2
3 import java.util.Random;
4
5 public class MyRandom
6 {
7
8 public static void main(String[] args)
9 {
10 // TODO Auto-generated method stub
11 int[] randArray = new int[5];
12 int randInt = 0;// 产生的随机数
13 int count = 0;// 产生合格随机数的个数
14 boolean flag = false;// 标记产生的随机数是否重复
15 Random rand = new Random();
16 while (count < 5)
17 {
18 randInt = rand.nextInt(11);
19 for (int i = 0; i < count; i++)
20 {
21 if (randArray[i] == randInt)
22 {
23 flag = true;
24 break;
25 }
26 else
27 {
28 flag = false;
29 }
30 }
31 if (!flag && randInt != 0)
32 {
33 randArray[count++] = randInt;
34 }
35 }
36 for (int x : randArray)
37 System.out.println(x);
38
39 }
40
41 }

方法二:使用容器

View Code
 1 package com.study.pratice03;
2
3 import java.util.ArrayList;
4 import java.util.List;
5 import java.util.Random;
6
7 public class SetRandom
8 {
9
10 public static void main(String[] args)
11 {
12 // TODO Auto-generated method stub
13 List<Integer> list = new ArrayList<Integer>();
14 Random rd = new Random();
15 int count = 0;
16 while (count < 5)
17 {
18 int randInt = rd.nextInt(11);
19 if (randInt != 0 && !list.contains(randInt))
20 {
21 list.add(randInt);
22 count++;
23 }
24 }
25 for (Integer inte : list)
26 System.out.println(inte);
27 }
28 }




原文地址:https://www.cnblogs.com/xiongyu/p/2266500.html