I have implemented those two methods described as in 1
and 2
.
I appreciate any kind of review to improve my method implementation.
Implement the method
toString
.
toString
returns a string representation of the listImplement the method
remove
.
remove
removes a given course from the list. If the course is not in the list, the list is not updated.When the code is executed, the following printout is generated:
<10, Algebra>
<20, Algorithms>
<30, Electronics>
<40, Physics>
<50, Programming>
After the implemented methods call.
<10, Algebra>
<20, Algorithms>
<50, Programming>
public class CourseList {
private static final int CAPACITY = 5;
// courses
private Course[] courses;
// the number of courses
private int courseCount;
public CourseList() {
courses = new Course[CAPACITY];
courseCount = 0;
}
// add adds a course to the list
public void add(Course course) {
courses[courseCount] = course;
courseCount++;
}
public void remove (Course course) {
int courseIndex = -1;
for (int i = 1; i < courseCount; i++)
if (courses[i].equals(course)) {
courseIndex = i;
break;
}
if (courseIndex != -1) {
for (int i = courseIndex; i < courseCount - 1; i++)
courses[i] = courses[i + 1];
courses[courseCount - 1] = null;
}
}
public String toString(){
StringBuilder sb = new StringBuilder();
for(int i = 0; i< courses.length; i++){
sb.append(courses[i]);
sb.append("\n");
}
return sb.toString();
}
public static void main(String[] args) {
CourseList list = new CourseList();
list.add(new Course(10, "Algebra"));
list.add(new Course(20, "Algorithms"));
list.add(new Course(30, "Electronics"));
list.add(new Course(40, "Physics"));
list.add(new Course(50, "Programming"));
System.out.println(list);
list.remove(new Course(40, "Physics"));
list.remove(new Course(30, "Electronics"));
System.out.println(list);
}
}