生成一套多对多的学生选课代码 java
时间: 2024-05-01 11:24:11 浏览: 11
以下是一个简单的多对多学生选课代码示例,使用Java语言实现:
```java
import java.util.ArrayList;
public class Course {
private String courseName;
private int courseId;
private ArrayList<Student> students;
public Course(String courseName, int courseId) {
this.courseName = courseName;
this.courseId = courseId;
this.students = new ArrayList<Student>();
}
public String getCourseName() {
return courseName;
}
public int getCourseId() {
return courseId;
}
public ArrayList<Student> getStudents() {
return students;
}
public void addStudent(Student student) {
students.add(student);
}
}
public class Student {
private String name;
private int studentId;
private ArrayList<Course> courses;
public Student(String name, int studentId) {
this.name = name;
this.studentId = studentId;
this.courses = new ArrayList<Course>();
}
public String getName() {
return name;
}
public int getStudentId() {
return studentId;
}
public ArrayList<Course> getCourses() {
return courses;
}
public void addCourse(Course course) {
courses.add(course);
course.addStudent(this);
}
}
public class Main {
public static void main(String[] args) {
Course math = new Course("Math", 101);
Course science = new Course("Science", 102);
Course history = new Course("History", 103);
Student john = new Student("John", 1);
Student sarah = new Student("Sarah", 2);
Student tom = new Student("Tom", 3);
john.addCourse(math);
john.addCourse(history);
sarah.addCourse(math);
sarah.addCourse(science);
tom.addCourse(history);
System.out.println(john.getName() + " is taking:");
for (Course course : john.getCourses()) {
System.out.println(course.getCourseName());
}
System.out.println(sarah.getName() + " is taking:");
for (Course course : sarah.getCourses()) {
System.out.println(course.getCourseName());
}
System.out.println(tom.getName() + " is taking:");
for (Course course : tom.getCourses()) {
System.out.println(course.getCourseName());
}
}
}
```
在这个示例中,我们定义了两个类:Course和Student。Course类表示一门课程,包含课程名称、课程ID和学生列表。Student类表示一个学生,包含学生姓名、学生ID和选课列表。
在Main类中,我们创建了三个课程和三个学生,并将学生添加到相应的课程中。然后,我们打印每个学生所选的课程列表。