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

题目:生成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/archive/2011/11/28/2266500.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值