(类库使用案例分析)随机数组

利用Random类产生5个1-30之间(包括1和30)的随机整数

  •  产生随机数组类
    class NumberFactory{
        private static Random random = new Random();
        /**
         * 通过随机数生成一个数组的内容,该内容不包括有0
         * @param length 要开辟的空间大小
         * @return  生产的数组
         */
        public static int[] create(int length){
            int data[] = new int[length];
            int foot = 0;
            while (foot < data.length){
                int num = random.nextInt(30);   //不超过30的随机数
                if(num != 0){
                    data[foot++] = num; // 保存数据
                }
            }
            return data;
        }
    }
  • 主方法
    public static void main(String[] args) {
            int[] result = NumberFactory.create(5);
            for (int x:result){
                System.out.println(x);
            }
        }

    11
    15
    5
    9
    11

 

猜你喜欢

转载自blog.csdn.net/weixin_46245201/article/details/112724603