Revise the Course class as follows: -The array size is fixed in listing 10.6. Im
ID: 3528200 • Letter: R
Question
Revise the Course class as follows: -The array size is fixed in listing 10.6. Improve it to automatically increase the array size by creating a new larger array and copying the contents of the current array to it. -Implement the dropStudent method. -Add a new method named clear() that removes all students from the course. Write a test program that creates a course, add three student, removes one, and displays the students in the course. Here's listing 10.6: public class Course { private String courseName; private String[] students = new String[100]; private int numberOfStudents; public Course(String courseName) { this.courseName = courseName; } public void addStudent(String student) { students[numberOfStudents] = student; numberOfStudents++; } public String[] getStudents() { return students; } public int getNumberOfStudents() { return numberOfStudents; } public String getCourseName() { return courseName; } public void dropStudent(String student) { // Left as an exercise in Exercise 9.9 } }Explanation / Answer
Course.java
import java.util.ArrayList;
public class Course {
private String courseName;
private ArrayList<String> students = new ArrayList<String>();
private int numberOfStudents;
public Course(String courseName) {
this.courseName = courseName;
this.numberOfStudents = 0;
}
public void addStudent(String student) {
numberOfStudents++;
students.add(student);
}
public ArrayList<String> getStudents() {
return students;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public String getCourseName() {
return courseName;
}
public void dropStudent(String student) {
for (int i = 0; i < students.size(); i++) {
if (student.equalsIgnoreCase(students.get(i))) {
students.remove(i);
}
}
}
public void clear() {
students.clear();
}
}
TestCourse.java
import java.util.ArrayList;
import java.util.Scanner;
public class TestCourse {
public static void main(String[] args) {
String name;
Scanner input = new Scanner(System.in);
Course c = new Course("Math");
c.addStudent("Mack");
c.addStudent("Rahul");
c.addStudent("John");
ArrayList<String> students = c.getStudents();
System.out.println("List of Students :");
for (int i = 0; i < students.size(); i++) {
System.out.println(students.get(i));
}
System.out
.println(" Enter the Name of student to whome you want to drop :");
name = input.next();
c.dropStudent(name);
System.out.println(" List of Students After Removal:");
for (int i = 0; i < students.size(); i++) {
System.out.println(students.get(i));
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.