Skip to content

Commit 50180f0

Browse files
authored
Add files via upload
1 parent b9362ee commit 50180f0

File tree

1 file changed

+88
-0
lines changed

1 file changed

+88
-0
lines changed
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
package ch_10;
2+
3+
import java.util.Arrays;
4+
import java.util.Objects;
5+
6+
/**
7+
* Write a test program that creates a course, adds three students, removes one,
8+
* and displays the students in the course.
9+
*/
10+
public class Exercise10_09 {
11+
public static void main(String[] args) {
12+
Course statistics = new Course("Statistics 341");
13+
statistics.addStudent("Jillian Frometorgai");
14+
statistics.addStudent("Shrezen Maticut");
15+
statistics.addStudent("Phi Wazi");
16+
statistics.dropStudent("Jillian Frometorgai");
17+
18+
System.out.println("Students in the course " + statistics.getCourseName() + " are: ");
19+
for (String s : statistics.getStudents()) {
20+
if (Objects.nonNull(s)) {
21+
System.out.print(s + " ");
22+
}
23+
}
24+
}
25+
}
26+
/**
27+
* **10.9 (The Course class) Revise the Course class as follows:
28+
* ■ The array size is fixed in Listing 10.6. Improve it to automatically increase
29+
* the array size by creating a new larger array and copying the contents of the
30+
* current array to it.
31+
* ■ Implement the dropStudent method.
32+
* ■ Add a new method named clear() that removes all students from the
33+
* course.
34+
*/
35+
class Course {
36+
private String courseName;
37+
private String[] students = new String[100];
38+
private int numberOfStudents;
39+
40+
public Course(String courseName) {
41+
this.courseName = courseName;
42+
}
43+
44+
public void addStudent(String student) {
45+
if (student.length() < (numberOfStudents + 1)) {
46+
students = Arrays.copyOf(students, students.length * 2);
47+
}
48+
students[numberOfStudents] = student;
49+
numberOfStudents++;
50+
System.out.println("Added student: " + student + " to the course: " + getCourseName());
51+
}
52+
53+
public String[] getStudents() {
54+
return students;
55+
}
56+
57+
public int getNumberOfStudents() {
58+
return numberOfStudents;
59+
}
60+
61+
public String getCourseName() {
62+
return courseName;
63+
}
64+
65+
/**
66+
* ■ Implement the dropStudent method.
67+
*
68+
* @param student to drop
69+
*/
70+
public void dropStudent(String student) {
71+
for (int i = 0; i < numberOfStudents; i++) {
72+
if (students[i].equals(student)) {
73+
students[i] = null;
74+
break;
75+
}
76+
}
77+
System.out.println("Dropped student: " + student + " has been dropped from " + getCourseName());
78+
}
79+
80+
/**
81+
* ■ Add a new method named clear() that removes all students from the
82+
*/
83+
protected void clear() {
84+
Arrays.fill(students, null);
85+
}
86+
87+
88+
}

0 commit comments

Comments
 (0)