java se 随机数。生成
发布日期:2022-03-29 14:05:00
浏览次数:35
分类:博客文章
本文共 2486 字,大约阅读时间需要 8 分钟。
public class test { public static void main(String[] args) { getRandomNum1(); getRandomNum2(); getRandomNum3(); getRandomNum4(); getRandomNum5(); } /** * 对数组里面的数字进行循环判断,如果有不做处理,继续循环。没有就添加。 */ private static void getRandomNum1() { int [] arr = new int[5]; int count = 0; while(count < 5) { int num = (int) (Math.random() * (10)) ; boolean flag = true; for (int j = 0; j < 5; j++) { if(num == arr[j]){ flag = false; break; } } if(flag){ arr[count] = num; count++; } } System.out.println("随机数1:"+Arrays.toString(arr)); } /** * 判断是否存在。不在就添加,在就不处理。继续循环 */ private static void getRandomNum2() { List list = new ArrayList(); while(list.size() < 5) { int num = (int) (Math.random() * (10)) ; if(!list.contains(num)) { list.add(num); } } System.out.println("随机数2:"+Arrays.toString(list.toArray())); } /** * 利用set特性.自动去重 */ private static void getRandomNum3() { Set set = new TreeSet<>(); while(set.size() < 5) { int num = (int) (Math.random() * (10)) ; set.add(num); } System.out.println("随机数3:"+Arrays.toString(set.toArray())); } /** * 利用map特性做空判断 */ private static void getRandomNum4() { Map map = new HashMap<>(); while(map.size() < 5) { int num = (int) (Math.random() * (10)) ; if(map.get(num) == null ) { map.put(num,num); } } System.out.println("随机数4:"+map.values()); } /** * 批量生成随机数,取随机的5个 */ private static void getRandomNum5() { int[] arrs = new int[20]; for (int i = 0; i < arrs.length; i++) { arrs[i] = i ; } int[] arr = new int[5]; boolean[] flag = new boolean[arrs.length]; Random random=new Random(); int j = 0; for (int i = 0; i < arr.length; i++) { do { j = random.nextInt(flag.length); } while (flag[j]); //标记,如果取出来过就继续do while 只有不符合while才会继续 flag[j] = true; arr[i]=arrs[j]; } System.out.println("随机数5:"+Arrays.toString(arr)); }}
转载地址:https://www.cnblogs.com/1-Admin/p/9199400.html 如侵犯您的版权,请留言回复原文章的地址,我们会给您删除此文章,给您带来不便请您谅解!
发表评论
最新留言
初次前来,多多关照!
[***.217.46.12]2024年04月12日 13时31分53秒
关于作者
喝酒易醉,品茶养心,人生如梦,品茶悟道,何以解忧?唯有杜康!
-- 愿君每日到此一游!
推荐文章
Emacs-061-org-mode中在不同标题间跳转
2019-04-27
Emacs-064-Emacs中使用VIM的编辑模式
2019-04-27
Emacs-065-evil模式中插入与普通模式切换
2019-04-27
Emacs-068-evil中跳转到Buffer开头或者结尾
2019-04-27
Emacs-069-evil中插入操作
2019-04-27
Emacs-070-evil中追加操作
2019-04-27
Emacs-087-提示组合键
2019-04-27
Emacs-089-spacemacs查看版本号
2019-04-27
Emacs-093-spacemacs快速进入命令输入模式
2019-04-27
Emacs-094-spacemacs创建自己的layer
2019-04-27
Emacs-095-sapcemacs快速打开自己的配置文件
2019-04-27
Emacs-096-sapcemacs加载某些layer
2019-04-27
unix-007-在Windows上生成使用GNU gcc的Makefile
2019-04-27
c++-001-变量初始化
2019-04-27
Emacs-101-快捷注释
2019-04-27
Emacs-102-spacemacs使用vim导航键在文件清单中移动
2019-04-27
Emacs-103-使用spacemacs自带配置显示行号
2019-04-27
Emacs-204-company popup功能失效
2019-04-27
Emacs-205-Emacs的管理模块化
2019-04-27
Emacs-206-Windows上实现org-pomodoro的声音提示播放
2019-04-27