-2

我正在尝试将我生成的所有随机数放入 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]

有人知道怎么做吗?

4

1 回答 1

3

如果要在数组已满时打印数组,请将 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);
     }
于 2013-01-06T08:07:11.710 回答