【问题标题】:Why isnt my Random array returning random values? [closed]为什么我的随机数组不返回随机值? [关闭]
【发布时间】:2018-02-28 15:41:35
【问题描述】:

好的,基本上,我想做的是创建并打印一个包含 100 个随机数的数组。我的尝试似乎失败了......而不是得到 100 个随机数,我似乎得到了从 0 到 99 的数字。有人可以解释我如何解决这个问题吗?非常感谢。

public static void enterRandom()
{
    System.out.println("Welcome to the random number generator and arranger!");
    System.out.println("Now, watch me generate 100 random numbers, and print them in order...");
    System.out.println("...");
    System.out.println("...");
    System.out.println("...");

    Random what = new Random ();
    int[] store = new int [100];

    for (int i = 0; i <= store.length; i++)
    {
        store[i] = what.nextInt(100); //not in random?
        System.out.println(i);
    }

    return;
}

}

【问题讨论】:

  • System.out.println(i); - 你正在打印计数器。
  • 打印数组而不是计数器 System.out.println(store[i]);
  • 1.你打印错了,2.return 是多余的,3.i &lt;= 不会有好的结局。 (3) 没有导致异常的事实让我怀疑你没有运行代码,只是为了好玩而提问。
  • @Bathsheba 或者他们这样做了,现在忽略了异常
  • @FedericoklezCulloca:我希望如此。

标签: java arrays for-loop random


【解决方案1】:

正如所有 cmets 所述,您打印的是变量 i,而不是数组中的当前索引。所以,用System.out.println(store[i]);替换System.out.println(i);

要修复 ArrayIndexOutOfBounds 异常,请将 for (int i = 0; i &lt;= store.length; i++) 替换为 for (int i = 0; i &lt; store.length; i++)

【讨论】:

  • 为什么投反对票?
  • 我没有投反对票,但通常我们不会回答解决方案类似于拼写错误的问题。出于这个原因,我不同意关闭它,但这可以解释反对票。此外,答案已经在 cmets 中(如您所说),因此人们可能会认为您的回答是为了轻松业力。
  • @FedericoklezCulloca 我明白了。我应该删除我的答案吗?
  • 这取决于你,我猜。还有其他人想插话吗?
  • @pjs 剽窃:将他人的作品或想法当作自己的作品或想法冒充的做法。我在任何地方都没有做过这样的事情。此外,我的编辑解决了与其他人相同的错误。
猜你喜欢
  • 1970-01-01
  • 2018-11-23
  • 1970-01-01
  • 1970-01-01
  • 2013-09-26
  • 2018-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多