为什么我得到一个超出范围的数组异常,为什么我只生成数字0?

时间:2018-02-03 01:40:59

标签: java arrays random

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种不同的方式获得随机整数,结果每次都相同。

2 个答案:

答案 0 :(得分:4)

循环后的行System.out.println(scores1[index]); - 循环条件为index <= 6,这意味着index现在为7。因此它超出了范围。我想你想要System.out.println(Arrays.toString(scores1));

答案 1 :(得分:2)

    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++;
    }

For this line you should rewrite like this. Because index always starts from 0 in array and you are trying to fetch data at index 7 which is not present in array.

 System.out.println(scores1[index-1]);