ol Problem 7 12 points): Based on the following description, write a Java class.
ID: 3735835 • Letter: O
Question
ol Problem 7 12 points): Based on the following description, write a Java class. The courses in Metrostate are represented by Course objects. Each Course has a name of the course, the number of students registered for the course, and an array of string that contains the name Course should conta of each student (you can set the array size to 100). Thus, the class in three instance variables: String courseName, String[l students- new String[100], and int numberOfStudents. A Course is created by passing a course initializeshon below. When a new Course object is created, the number of Course csl low. When a new Course object is created, the number of students is n this case, the course name is "icS 141-01 Programming with Object." name as initialized to O. I = new Course("ICs i 41-01 Programming with Object"); The class must be designed in such a way that it returns a reasonable representation of the Course object as the following example shows (the registered number is just one o possible values). >System.out.printin(cs1); Course ICS 141-01 Programming with Object. Number of student registered 10. The class must have a method named addStudent, which is called when a student registers the course. The method accepts student name as a parameter. The number o students registered must then be incremented by 1. The method does not return anything The following code registers cs1. a new student named Michael to the newly created courseExplanation / Answer
public class Course {
private String courseName;
private String[] students = new String[1];
private int numberOfStudents;
public Course(String courseName) {
this.courseName = courseName;
}
public void addStudent(String student) {
if(numberOfStudents < students.length){
students[numberOfStudents] = student;
numberOfStudents++;
} else {
String[] tempStudents = new String[students.length + 1];
for (int i = 0; i < students.length; i++) {
tempStudents[i] = students[i];
}
students = tempStudents;
students[numberOfStudents] = student;
numberOfStudents++;
}
}
public String[] getStudents() {
return students;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public String getCourseName() {
return courseName;
}
public void dropStudent(String student) {
String[] tempStudents = new String[numberOfStudents];
for(int i = 0; i < students.length; i++) {
if(!students[i].equals(student)) {
tempStudents[i] = students[i];
}else{
numberOfStudents--;
}
}
students = tempStudents;
}
public void clear(){
for (int i = 0; i < students.length; i++) {
students[i] = null;
numberOfStudents = 0;
}
}
public static void printArray(String[] anArray) {
for (int i = 0; i < anArray.length; i++) {
if (i > 0) {
System.out.print(", ");
}
System.out.print(anArray[i]);
}
}
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.