【问题标题】:put random number in the array list java [closed]将随机数放入数组列表java [关闭]
【发布时间】:2013-01-06 08:03:09
【问题描述】:

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

有人知道怎么做吗?

【问题讨论】:

  • System.out.println 语句移到 for 循环之外。
  • 好的......谢谢......它正在工作......只要意识到就这么简单:D

标签: java arrays random arraylist


【解决方案1】:

如果要在数组已满时打印数组,请将 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-05-15
    • 1970-01-01
    • 1970-01-01
    • 2017-09-27
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    • 2014-05-30
    • 1970-01-01
    相关资源
    最近更新 更多