The array is actually initialized, to 100 null Student objects, indexed 0 to 99.
So, assuming that the enroll() method is part of the Course class, returning true whenever it stores a non-null Student object, it can be implemented as follows:
public boolean enroll(Student s) {
if ((s == null) || (this.counter >= 100)) {
return false;
}
this.students[this.counter] = s;
++this.counter;
return true;
}
where this.counter is an integer initialized to 0 in the constructor, after the students array is initialized.
A better approach would have been to use an ArrayList instead of an array, to avoid having to check the size every time and have no maximum size limitation. In that case, this.students would be initialized as
List<Student> students;
...
this.students = new ArrayList<Student>();
and the implementation of enroll() would be simplified to
public boolean enroll(Student s) {
if (s == null) {
return false;
}
this.students.add(s);
return true;
}
without the need for a counter.
ArrayListwhich can grow as needed. To implement it with an array, though, you just need to keep track ofnumStudentsso that you know what index to put a new student at.new Student[100].students[i] = new Student();