vendredi 2 février 2018

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.




Aucun commentaire:

Enregistrer un commentaire