SeatingChart
is #3 from the from the 2014 AP Computer Science A Free Response problems.
https://secure-media.collegeboard.org/digitalServices/pdf/ap/ap14_frq_computer_science_a.pdf
Part (a) SeatingChart
constructor
public SeatingChart(List<Student> studentList, int rows, int cols)
{
seats = new Student[rows][cols];
int sIndex = 0;
for(int c = 0; c < seats[0].length; c++)
{
for(int r = 0; r < seats.length; r++)
{
if(sIndex < studentList.size())
{
seats[r][c] = studentList.get(sIndex);
sIndex++;
}
}
}
}
When writing a constructor for a class that stores an array or ArrayList
as an instance variable, make sure to actually initialize the variable. It is common for students to omit the first line entirely and incorrectly assume that adding/setting initializes the array/list. As with all constructors, make sure to initialize the instance variable rather than incorrectly declaring a new local variable.
See 2D array exercises for additional traversals and other challenges.
Part (b) removeAbsentStudents
method
public int removeAbsentStudents(int allowedAbsences)
{
int removed = 0;
for(int r = 0; r < seats.length; r++)
{
for(int c = 0; c < seats[0].length; c++)
{
if(seats[r][c] != null && seats[r][c].getAbsenceCount() > allowedAbsences)
{
seats[r][c] = null;
removed++;
}
}
}
return removed;
}
2014 AP CS Exam Free Response Solutions
- scrambleWord and scrambleOrRemove free response solution
- Director free response solution
- Trio free response solution
Additional resources for 2D arrays
- Intro to 2D arrays
- 2D array exercises
- Mazer free response
- Droppy free response
- Flight free response
- MatrixManipulator exercise
Help & comments
Get help from AP CS Tutor Brandon Horn