简体   繁体   中英

Why am I getting an array out of bounds exception, and why am I only generating the number 0?

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]);
    }
}

I am confused as to why I am getting the exception. I can fix this by changing the size of the array to 8, but I shouldn't have to do that. Also when it is changed to 8, the output is all 0's. I have used 3 different ways of getting a random integer and the outcome is the same every time.

Line after the loop, System.out.println(scores1[index]); - the loop condition is index <= 6 which means index is now 7 . Thus it is out of range. I think you wanted System.out.println(Arrays.toString(scores1));

    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]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM