The class CourseList implements a simple database of students registered in a course. Complete the method countAttendees in the code below such that it returns the number of students in the instance of CourseList who have not attended any classes. Your response may be written in Java or pseudocode. Your code cannot modify the linked list. The class Node is similar to the linked list node object discussed in lecture. You can use helper methods, but this is not necessary.
class Student {
protected int studentNumber;
protected int classesAttended;
public Student (int newStudentNumber) {
studentNumber =
newStudentNumber;
classesAttended =
0;
}
public int getClassesAttended () { return classesAttended; }
public void attendClass () {
classesAttended++; }
}
class Node<E> {
protected E value;
protected Node<E> next;
public Node (E newValue, Node<E>
newNext) {
value = newValue;
next = newNext;
}
public E getValue () { return value; }
public Node<E> getNext () { return next;
}
}
public class CourseList {
Node<Student> head;
public CourseList () { head = null; }
public void addStudent (Student newStudent) { head = new Node<Student>(newStudent, head); }
public int countAttendees () {
Solution:
Java code:
public int countAttendees () {
// Make a new object storing head
Node<Student> p = head;
// Initialise count to 0
int count = 0;
// Iterate over list of student nodes, till p becomes null
while(p!=null){
// Fetch student details from node
Student s = p.getValue();
// If student attended no class increment count
if(s.getClassesAttended() == 0)
count += 1;
// Move to next student in the list
p = p.getNext();
}
// return number of students who have not attended any class
return count;
}
Screenshot of code to understand indentation:
PS: Let me know if you have any doubt
Get Answers For Free
Most questions answered within 1 hours.