生成不重复的随机数(待完善)
2016-01-15 20:08
393 查看
// 方法一,用for循环,break跳出语句(不推荐,方法太笨,思路也不是很明确) public static void main(String[] args) { // 方法二 利用foreach和continue循环并跳出循环 int[] c = new int[7];// 创建7个数的数列,这个地方可以不用定义数组 Random ran1 = new Random(); // 实例化对象 boolean bo = false; // 定义标识符来控制循环 for (int i = 0; i < c.length; i++) { // 生成随机数列,并且一次性判断是不是有0和有没有相同的数 // 利用遍历数组的方法判断是不是有重复的数字 int t = ran1.nextInt(35); if (t == 0) { // 判断是不是有0这个数字 i--; continue; } for (int y : c) { if (y == t) { bo = true; break; } } if (bo) { i--; continue; } c[i] = t; } for (int x1 : c) { System.out.print(x1 + " "); } System.out.println(); // 利用index来判断是不是有相同的数列(推荐) String str = ""; for (int i = 0; i < 7; i++) { int t = ran1.nextInt(35); if (t == 0) { // 判断是不是有0这个数字 i--; continue; } if (str.indexOf(t + "") >= 0) { // 判断是不是有重复的数字 i--; continue; } str = str + t + " "; } System.out.println(str); System.out.println("------------------"); // 利用replace替换,这个方法虽然简单但是不是很好,每个数不是很随机了,还没有想到处理的方法 String s = "01 02 03 04 05 06 07 08 09 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25" + " 26 27 28 29 30 31 32 33 34 35";// 这种方法尽量不要用显得太Low了 Random r = new Random(); for (int i = 0; i < 100; i++) { int t1 = r.nextInt(36); if (t1 <= 9) { s = s.replace("0" + t1 + " ", ""); } else { s = s.replace(t1 + " ", ""); } if (s.length() <= 22) { System.out.println(s); break; } //还有其他的方法,还没有整理
相关文章推荐
- windows 系统 安装 net-snmp 并成功运行命令的步骤
- Codeforces Round #339 (Div. 2) B. Gena's Code
- 【UEditor】百度UE富文本自定义按钮添加文本
- python day11
- UML顺序图和通信图
- 11gR2(11.2) RAC TAF Configuration for Admin and Policy Managed Databases (文档 ID 1312749.1)
- 数据库存储过程
- 学习 ...
- Codeforces Round #339 (Div. 2) A. Link/Cut Tree
- java基础总结
- There is no Action mapped for namespace [/] and action name [user!add] associated with context path
- loadView 再思考
- Android UI之ImageSwitcher && TextSwitcher 实现图文翻页
- 指针数组和数组指针的声明形式
- zookeeper的集群模式下的安装和配置
- 自己做的一个输入输出缓冲池
- Jenkins+Maven+Git CI环境搭建手册
- 对象封装属性的真正源头
- 离散数学及其应用 前言
- Django+Query