A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 結断的时光 中级黑马   /  2016-5-28 23:29  /  562 人查看  /  4 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

编写一个程序,获取10个1至20的随机数,要求随机数不能重复。

4 个回复

倒序浏览

回帖奖励 +10

public static void main(String[] args) {
                HashSet<Integer> hs = getRandom();
                System.out.println(hs.toString());
        }
        public static HashSet<Integer> getRandom() {
                Random r = new Random();
                HashSet<Integer> hs = new HashSet<Integer>();
                while(hs.size()<10){
                        hs.add(r.nextInt(20)+1);                       
                }
                return hs;
        }
回复 使用道具 举报
本帖最后由 liming1990422 于 2016-5-28 23:39 编辑

public static void main(String[] args) {
                Random r = new Random();
                Set<Integer> si = new TreeSet<Integer>();
               while(si.size()<10){
               si.add(r.nextInt(20)+1);
            
        }
                System.out.println(si);
        }
回复 使用道具 举报
import java.util.ArrayList;
import java.util.Collections;

public class Demo111 {
        public static void main(String[] args) {
                //编写一个程序,获取10个1至20的随机数,要求随机数不能重复。
                ArrayList<Integer> al = new ArrayList<>();
                while (true) {
                        //将随机数转化为int类型
                        int temp = (int)(Math.random()*20 + 1);
                        //当集合不包含这个随机数就添加
                        if (!al.contains(temp)) {
                                al.add(temp);
                        }
                        //当集合长度为10就跳出循环
                        if (al.size() == 10) {
                                break;
                        }
                }
                //排序
                Collections.sort(al);
                System.out.println(al);
        }       
}
回复 使用道具 举报
看的好晕。。表示才刚看到集合
回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马