I need to create a List of students and convert them into a Seating Chart (2d array of specific length and width). Here is my code:
public class SeatingChart {
Student seats[][];
public SeatingChart(List <Student> studentList, int rows, int cols) {
seats = new Student[rows][cols];
for (int i = 0; i < cols; i++) { //Assigns Students in Column by Row order
for (int j = 0; j < rows; j++) {
if (i*rows+j > studentList.size() - 1) {
seats[i][j] = null; //Occupies remaining `seats` with null
}
seats[i][j] = studentList.get(i*rows+j); //Finds an error with this line
}
}
}
public class Tester {
public static void main (String[] args) {
List <Student> classroom = new ArrayList<Student>();
classroom.add(new Student("Anna", 3));
SeatingChart sc = new SeatingChart(classroom, 2, 2); //Finds an error with this line
}
}
public class Student {
//assigns Name and number of absences for each student
}
This returns:
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 1, Size: 1
at java.util.ArrayList.rangeCheck(ArrayList.java:657)
at java.util.ArrayList.get(ArrayList.java:433)
at stud2.SeatingChart.<init>(SeatingChart.java:14)
at stud2.SeatingChartTester.main(SeatingChartTester.java:12)
However, the errors which are part of the ArrayList class (rangeCheck and get) are gone once I add 2 more students to classroom
. Why is the error resolved, and why are the last 2 errors still present? I have double-checked the logic behind the code and replaced the 2D array with a 1D array of the same size as the ArrayList, but I'm getting the same error.