Good day. This is a homework question. I am required to create a course object using the constructor by using a course name. Students can be added by using addStudent (String student) method and return all the students for that course using getStudents() method. My test program requires me to display the number of student and students name for that courses as shown below: Number of students in Programming II course: 6
- Siti Aminah Muhammad
- Halim Zainal Abidin
- Jason Lim
- ...
- ... Number of Students in Database Systems course: 15
- Fatimah Ahmad
- Sarah Goh ...
However, when I run my test program, the names are output as null and I can't figure out why. Below is my code:
public class Course {
private String name;
private int numberOfStudents;
private String[] students = new String [100];
public Course() {
}
public Course(String name) {
this.name = name;
}
public void addStudent(String student) {
students [numberOfStudents] = student;
}
public String[] getStudents() {
return students;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public void setNumberOfStudents(int NumberOfStudents) {
this.numberOfStudents = NumberOfStudents;
}
public String getName() {
return name;
}
}
public class TestCourse {
public static void main(String[] args) {
Course course1 = new Course("Programming II");
course1.setNumberOfStudents(6);
System.out.println("Number of students in Programming II Course: " +course1.getNumberOfStudents());
String[] students = course1.getStudents();
course1.addStudent("Siti Aminah Muhammad");
course1.addStudent("Halim Zainal Abidin");
course1.addStudent("Jason Lim");
for (int i= 1; i<course1.getNumberOfStudents(); i++)
System.out.println( +i+ "." +students[i]);
Course course2 = new Course("Database Systems");
course2.addStudent("Fatimah Ahmad");
course2.addStudent("Sarah Goh");
course2.setNumberOfStudents(15);
System.out.println("Number of students in Database Systems Course:" +course2.getNumberOfStudents());
for (int i= 1; i<course2.getNumberOfStudents(); i++)
System.out.println( +i+ "." +students[i]);
}
}
students [numberOfStudents] = student, this would write to only6index and while printing you are printing index less than 6, so before 6 every index have null value in array