【发布时间】:2018-07-13 13:42:00
【问题描述】:
public class ArraysList {
public static void main(String[] args) {
int[] scores1;
int[] scores2;
scores1 = new int[7];
scores2 = new int[7];
int index = 0;
while (index <= 6) {
scores1[index] = ThreadLocalRandom.current().nextInt(1, 10 + 1);
scores2[index] = ThreadLocalRandom.current().nextInt(1, 10 + 1);
index++;
}
System.out.println(scores1[index]);
}
}
我对为什么会收到异常感到困惑。我可以通过将数组的大小更改为 8 来解决此问题,但我不应该这样做。此外,当它更改为 8 时,输出全为 0。我使用了 3 种不同的方法来获取随机整数,并且每次的结果都是相同的。
【问题讨论】:
-
因为您的数组中的有效数组索引是 0 到 6 包括在内,而您使用的是 7。