学生选课)根据下面的类图,编写课程Course类和学生Student类。并用题目给出的测试类Test进行测试。不允许改动题目提供的测试类Test代码。Course类说明如下:(1)addStudent()方法用于添加一个选课的学生;(2)dropStudent()方法用于删除一个选课的学生;(3)toStrin()g方法用于返回课程的所有信息,包括课程名称和选课学生。Student类说明如下:(1)toString()方法用于返回学生的信息。(2)equals()方法用于判断两个学生是否为同一个学生。注意equals()方法的参数类型。
时间: 2023-11-22 14:56:01 浏览: 94
简单的学生选课系统,新手可以看看
4星 · 用户满意度95%
根据上述要求,可以编写如下的Course类和Student类:
Course类:
```java
import java.util.ArrayList;
import java.util.List;
public class Course {
private String name;
private List<Student> students;
public Course(String name) {
this.name = name;
this.students = new ArrayList<>();
}
public String getName() {
return name;
}
public void addStudent(Student student) {
students.add(student);
}
public void dropStudent(Student student) {
students.remove(student);
}
public List<Student> getStudents() {
return students;
}
@Override
public String toString() {
return "Course{" +
"name='" + name + '\'' +
", students=" + students +
'}';
}
}
```
Student类:
```java
public class Student {
private String name;
private int id;
public Student(String name, int id) {
this.name = name;
this.id = id;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", id=" + id +
'}';
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof Student)) {
return false;
}
Student other = (Student) obj;
return this.id == other.id;
}
}
```
测试类Test:
```java
public class Test {
public static void main(String[] args) {
Course math = new Course("Math");
Student alice = new Student("Alice", 1);
Student bob = new Student("Bob", 2);
Student charlie = new Student("Charlie", 3);
math.addStudent(alice);
math.addStudent(bob);
math.addStudent(charlie);
System.out.println(math);
// Output: Course{name='Math', students=[Student{name='Alice', id=1}, Student{name='Bob', id=2}, Student{name='Charlie', id=3}]}
math.dropStudent(bob);
System.out.println(math);
// Output: Course{name='Math', students=[Student{name='Alice', id=1}, Student{name='Charlie', id=3}]}
}
}
```
阅读全文