为什么我的Random数组不能返回随机值? [关闭]

问题描述 投票:0回答:1

好吧,基本上,我想要做的是创建并打印一个包含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;
}

}

java arrays for-loop random
1个回答
2
投票

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

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

© www.soinside.com 2019 - 2024. All rights reserved.