好吧,本质上,我想做的是创建并打印一个包含 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;
}
}
最佳答案
正如所有评论所述,您正在打印变量 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++)
关于java - 为什么我的随机数组不返回随机值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49033331/