把随机数放在数组列表java中

时间:2013-01-06 08:03:10

标签: java arrays random arraylist

我正在尝试将我生成的所有随机数放入arraylist并将所有随机数打印到单个数组中

    static int pick;
    public static void main(String[] args) {
        ArrayList al = new ArrayList(); 
        Random rand = new Random();

        for (int j = 0; j<10; j++)
        {
        pick = rand.nextInt(100);
        al.add(pick);
        System.out.println("Contents of al: " + al);
        }

从上面的函数我得到了像这样的结果

 Contents of al: [43]
 Contents of al: [43, 44]
 Contents of al: [43, 44, 3]
 Contents of al: [43, 44, 3, 66]
 Contents of al: [43, 44, 3, 66, 47]
 Contents of al: [43, 44, 3, 66, 47, 24]
 Contents of al: [43, 44, 3, 66, 47, 24, 12]
 Contents of al: [43, 44, 3, 66, 47, 24, 12, 35]
 Contents of al: [43, 44, 3, 66, 47, 24, 12, 35, 0]
 Contents of al: [43, 44, 3, 66, 47, 24, 12, 35, 0, 85]

我想要的预期输出只是上面结果的最后一行

 Contents of al: [43, 44, 3, 66, 47, 24, 12, 35, 0, 85]
谁知道怎么做?

1 个答案:

答案 0 :(得分:2)

如果要在阵列满时打印数组,请将println从循环中取出。

希望能回答你的问题

    static int pick;
    public static void main(String[] args) {
        ArrayList al = new ArrayList(); 
        Random rand = new Random();

        for (int j = 0; j<10; j++)
        {
            pick = rand.nextInt(100);
            al.add(pick);
        }

        System.out.println("Contents of al: " + al);
     }