java 将随机数放入数组列表java

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14180419/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 15:22:57  来源:igfitidea点击:

put random number in the array list java

javaarraysrandomarraylist

提问by Newbie Newbae

I'm trying to put all random number which I generated to the arraylist and print all the random number into single array

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

    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);
        }

from the above function I got the result like this

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

 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]

the expected output I want is just the last line of the above result

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

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

anyone know how to do it?

有人知道怎么做吗?

回答by Hagai

If you want print the array when it is full take the println out of the loop.

如果您想在数组已满时打印数组,请将 println 移出循环。

Hope that answers your question

希望这能回答你的问题

    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);
     }