用java5 设计一个名为 Course 的课程类,该类包括: 1) 一个私有字符串数据类型的课程名称 courseName 2) 一个存储该课程学生的私有字符串数组 students 3) 一个私有整型数据 numberOfStudents 表示学生个数(默认值:0) 4) 创建一个带特定名称的课程的构造函数 5) 一个返回课程名的方法 6) 给这门课程添加一个新同学的方法 7) 返回这门课程的学生的方法 8) 返回这门课程的学生人数的方法 9) 编写 dropStudent 方法取消一门课程中某个学生 10) 一个名为 clear()的方法,删掉选某门课程的所有学生。 编写一个测试程序,创建一门课程,添加三个学生.删除一个学生,然后显示这门 课程的学生。
时间: 2023-05-15 18:07:55 浏览: 162
好的,以下是 Course 类的代码:
```java
public class Course {
private String courseName;
private String[] students = new String[100];
private int numberOfStudents = 0;
public Course(String courseName) {
this.courseName = courseName;
}
public String getCourseName() {
return courseName;
}
public void addStudent(String student) {
students[numberOfStudents] = student;
numberOfStudents++;
}
public String[] getStudents() {
return students;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public void dropStudent(String student) {
int index = -1;
for (int i = 0; i < numberOfStudents; i++) {
if (students[i].equals(student)) {
index = i;
break;
}
}
if (index >= 0) {
for (int i = index; i < numberOfStudents - 1; i++) {
students[i] = students[i + 1];
}
numberOfStudents--;
}
}
public void clear() {
students = new String[100];
numberOfStudents = 0;
}
}
```
以下是测试程序的代码:
```java
public class TestCourse {
public static void main(String[] args) {
Course course = new Course("Java Programming");
course.addStudent("Alice");
course.addStudent("Bob");
course.addStudent("Charlie");
course.dropStudent("Bob");
String[] students = course.getStudents();
System.out.println("The students in " + course.getCourseName() + " are:");
for (int i = 0; i < course.getNumberOfStudents(); i++) {
System.out.println(students[i]);
}
}
}
```
输出结果为:
```
The students in Java Programming are:
Alice
Charlie
```
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241231044833.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)