-1

I'm trying to solve a java question of the typical locker problem:

where there is n lockers and n students and all lockers are closed. As the students enter, the first student, denoted S1, opens every locker. Then the second student, S2, begins with the second locker, denoted L2, and closes every other locker. (closes it if it was open, and opens it if it was closed). And so on, until student Sn changes Ln.

import java.util.Scanner;
public class Main {
    static Scanner sc=new Scanner(System.in);
    public static void main(String[] args) {

        int testcase = sc.nextInt();
        int students = sc.nextInt();
        boolean[] a = new boolean[students];
        for (int i = 0; i < students; i++)
            a[i] = false;

        int[] x = new int[testcase];
        for (int i = 0; i < testcase; i++)
            x[i] = sc.nextInt();
        for (int i = 0; i < students; i++) {
            for (int j = 1; j < students + 1; j++) {
                if((i + 1) * j <= students) {
                    a[(i + 1) * j - 1] =! a[(i + 1) * j - 1];
                }
            }
        }
        for (int i = 0; i < testcase; i++) {
            if (a[x[i] - 1] == false)
                System.out.println("close");
            else
                System.out.println("open");
        }
    }
}

this is the code that I made, and assuming that the testcase is more than 1, after showing the output of the first input (ex: 10 4) following error occurs without showing the second ouput: Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 999 at Main.main(Main.java:23)

Can anyone plz explain why such error is appearing? thanks!

Kyle
  • 15
  • 3

1 Answers1

0

An ArrayIndexOutOfBoundsException occurs when you are trying to access an index of an array that does not exist. For example:

int[] numbers = new int[] {1, 2, 3, 4, 5};

There are five numbers in the array having the indexes from 0 to 4. If you try to access index 5, which does not exist, an ArrayIndexOutOfBoundsException will occur. That is, when you do this:

System.out.println("The sixth number in the array is :" + numbers[5]);

You are accessing indexes by a counter variable (i), which may become larger than the existing indexes of the array.

I suspect the following line to cause the ArrayIndexOutOfBoundsException because of the error message found in your question (Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 999 at Main.main(Main.java:23)):

if (a[x[i] - 1] == false) // at least, this is the 23rd line in the question code

You need the values of i because it may be larger than the maximum index of x and if it is valid, then check x[i] - 1, which may exceed existing indexes of a.

Please note that every value < 0 will as well cause an ArrayIndexOutOfBoundsException because indexes start at 0 and can never be less.

deHaar
  • 17,687
  • 10
  • 38
  • 51