put random number in the array list java [closed]

时间秒杀一切 提交于 2019-12-31 07:56:19

问题


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?


回答1:


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

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


来源:https://stackoverflow.com/questions/14180419/put-random-number-in-the-array-list-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!