- #1
JonnyG
- 234
- 45
- Homework Statement
- Create method to add students to course array.
- Relevant Equations
- no equations
I am writing a class called "Course" in Java so that one can input students names, etc. Here is my relevant code for the Course class:
As a little test, I wrote in the main method:
The output was "jonathan", but I was expecting an error! Let me explain:
The array "students" is initialized to be of length 0. In the Course class method addStudent, look at the line
When i is initially equal to 0 and the line
is executed, there should be an out of bounds error because students[0] doesn't exist. Why do I not get an error?
Java:
public class Course {
private String courseName;
private String[] students = new String[0];
private int numberOfStudents = 0;
public Course(String courseName) {
this.courseName = courseName;
}
public void addStudent(String student) {
String[] studentsRevised = new String[students.length + 1];
for (int i = 0; i <= students.length - 1; i++)
studentsRevised[i] = students[i];
studentsRevised[studentsRevised.length - 1] = student;
numberOfStudents++;
students = studentsRevised;
}
Java:
Course course = new Course("math");
course.addStudent("jonathan");
for (String student : course.getStudents())
System.out.println(student);
The output was "jonathan", but I was expecting an error! Let me explain:
The array "students" is initialized to be of length 0. In the Course class method addStudent, look at the line
Java:
studentsRevised[i] = students[i].
Java:
studentsRevised[i] = students[i].
Last edited: