Design and implement a class called Course that represents a course taken at a s
ID: 3558398 • Letter: D
Question
Design and implement a class called Course that represents a course taken at a school. A course object should kept track of up to five students (as represented by the Student class from the previous question). The constructor of the Course class should accept only the name of the course. Provide a method called addStudent that accepts one Student parameter (the Course object should keep track of how many valid students have been added to the course). Provide a method called average that computes and returns the average of all students
Explanation / Answer
//Course.java
import java.util.ArrayList;
import java.util.List;
public class Course {
private String name;
private List<Student> students;
public Course(String name) {
this.name = name;
students = new ArrayList<Student>();
}
public void addStudent(Student student) {
students.add(student);
}
public void roll(){
System.out.println("Course: " + name);
System.out.println("Students:");
for(Student student : students){
System.out.println(" "
+ student.getLastName()
+ ", " + student.getFirstName());
}
}
}
//Student.java
public class Student {
private String lastName;
private String firstName;
public Student(String lastName, String firstName){
this.lastName = lastName;
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
// Driver.java
public class Driver {
public static void main(String[] args) {
Course course = new Course("CS");
course.addStudent(new Student("Gates", "Bill"));
course.addStudent(new Student("Jobs", "Steve"));
course.addStudent(new Student("Dell", "Michael"));
course.roll();
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.