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!