Hello all,
I'm working on an assignment that says the following.
"
- 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, adds three students, removes one, and displays the students in the course."
10.6 Listing
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 exercise; } } }
My Test Code based off of book
public static void main(String[] args) { Course course1= new Course("Business"); course1.addStudent("Jay"); course1.addStudent("Silent Bob"); course1.addStudent("Dante"); course1.dropStudent("Jay"); System.out.println("Number of students in course1: " +course1.getNumberOfStudents()); String[] students= course1.getStudents(); for (int i=0; i< course1.getNumberOfStudents(); i++) System.out.println(students[i] + " , ");} }
My adjusted 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) { students[numberOfStudents] = student; numberOfStudents--; } public void Clear(){ student.length= 0; } }
The problem I'm having is, for the first part of the question where I need to automatically increase the array size. I'm really not great at this stuff. I have tried breaking it down, but can't "get it", I guess.
I assume, it'd be a loop that checks to see if the student array is full and if so, do the increaseArray() part, by maybe multiplying the student array and then assigning it. I just don't know how to do it haha. Any advice or breadcrumbs would be appreciated.
My *best* attempt at the loop so far has been
if (students == students.length){
int bigArray = 2*students.length;
String increaseArray()= new String[students];
System.arraycopy(students, 0, increaseArray, 0, students.length);
students= increaseArray;
but,yeah... Doesn't seem to be right.