黑马程序员技术交流社区

标题: 产生10个1-100之间的随机数要求随机数不能重复!两种方法 [打印本页]

作者: 驰骋向前    时间: 2016-12-5 00:10
标题: 产生10个1-100之间的随机数要求随机数不能重复!两种方法
/*请编写程序,产生10个1-100之间的随机数要求随机数不能重复,并测试
需求:编写一个程序,获取10个1至100的随机数
要求随机数不能重复,并把最终的随机数输出到控制台。*/
public class sj {
    public static void main(String[] args) {
           
            method1();
            System.out.println("------------------------");
            method2();
           
               
        }
    //方法一
    private static void method1() {
                ArrayList<Integer> a =new ArrayList<Integer>();
                while(a.size() != 10){
                        int sj =new Random().nextInt(100)+1;
                        if (! a.contains(sj)){
                                a.add(sj);
                        }
                }
                for (Integer i : a) {
                        System.out.print(i+" ");
                }
                System.out.println();
        }
    //方法二
        private static void method2() {
                HashSet<Integer> h =new HashSet<Integer>();
                while(h.size()!=10){
                        int sj=(int)(Math.random()*100)+1;
                        if (! h.contains(sj)){
                                h.add(sj);
                        }
                }
                for (Integer i : h) {
                        System.out.print(i+" ");
                }
        }

       
}




欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2