我需要编写一个程序,用 25 到 80 之间的随机数填充数组,然后使用另一个 for 循环每次在新行上打印结果。我不确定为什么我会得到一些输出,然后在这段代码中出现错误。
int[] myIntArray = new int [20];
Random r = new Random();
for (int i = 0; i <= 20; i++){
int rand = r.nextInt(80 - 25) + 25;
myIntArray[i] = rand;
}
for (int i = 0; i <= 20; i++){
System.out.println(myIntArray[i]);
}
最佳答案
请您的数组大小为 20,但您要向其中放入 21 个元素,因此请尝试此操作
int[] myIntArray = new int [21];
Random r = new Random();
for (int i = 0; i <= 20; i++){
int rand = r.nextInt(80 - 25) + 25;
myIntArray[i] = rand;
}
for (int i = 0; i <= 20; i++){
System.out.println(myIntArray[i]);
}
关于java - 为什么我的 for 循环不能与数组一起正常工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36993658/