美文网首页
List集合系列文章(九) - ArrayList实现获取10

List集合系列文章(九) - ArrayList实现获取10

作者: 世道无情 | 来源:发表于2018-12-24 17:48 被阅读0次

1. 需求


获取10个 1-20之间的随机数,且不能重复:
思路:
1>:定义一个ArrayList集合,类型是Integer;
2>:定义统计变量 count,初始化值为0;
3>:如果 count<10,就将产生的随机数添加到集合中:
判断 产生的随机数是否在ArrayList中,如果存在,就不添加,如果不存在就添加,然后将count++;
4>:遍历ArrayList即可;

2. 代码如下:


    /**
     * 获取 10个 1-20以内的随机数,要求不能重复
     */
    private static void randomDemoTest() {
        // 1>:创建集合  ArrayList对象
        ArrayList<Integer> arrayList = new ArrayList<Integer>() ;

        // 2>:定义统计变量 count = 0 ;
        int count = 0 ;

        // 3>:如果 count<10,就将产生的随机数添加到 ArrayList集合
        while (count < 10){

            // 获取1-20以内的随机数
            int num = (int) (Math.random()*20 + 1);

            // 4>:如果 ArrayList集合中不包含 该随机数num,就添加
            if (!arrayList.contains(num)){
                arrayList.add(num) ;
                count++ ;
            }
        }

        for (Integer integer : arrayList) {
            System.out.println(integer);


            /*输出结果:
                    4
                    17
                    11
                    13
                    6
                    8
                    12
                    7
                    3
                    5*/
        }
    }

相关文章

网友评论

      本文标题:List集合系列文章(九) - ArrayList实现获取10

      本文链接:https://www.haomeiwen.com/subject/znltxqtx.html