用java写一个学生选课系统的代码
时间: 2023-12-09 10:50:09 浏览: 84
好的,我可以为您提供一个学生选课系统的Java代码示例。
代码如下:
```
import java.util.ArrayList;
class Student {
private String name;
private int id;
private ArrayList<Course> courses;
public Student(String name, int id) {
this.name = name;
this.id = id;
this.courses = new ArrayList<>();
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public ArrayList<Course> getCourses() {
return courses;
}
public void enroll(Course course) {
courses.add(course);
}
public void drop(Course course) {
courses.remove(course);
}
}
class Course {
private String name;
private int id;
private ArrayList<Student> students;
private int maxStudents;
public Course(String name, int id, int maxStudents) {
this.name = name;
this.id = id;
this.students = new ArrayList<>();
this.maxStudents = maxStudents;
}
public String getName() {
return name;
}
public int getId() {
return id;
}
public ArrayList<Student> getStudents() {
return students;
}
public int getMaxStudents() {
return maxStudents;
}
public boolean addStudent(Student student) {
if (students.size() < maxStudents) {
students.add(student);
return true;
} else {
return false;
}
}
public void removeStudent(Student student) {
students.remove(student);
}
}
public class Main {
public static void main(String[] args) {
Course course1 = new Course("Math", 101, 3);
Course course2 = new Course("Science", 102, 2);
Student student1 = new Student("John", 1);
Student student2 = new Student("Sarah", 2);
Student student3 = new Student("Tom", 3);
course1.addStudent(student1);
course1.addStudent(student2);
course1.addStudent(student3);
course2.addStudent(student1);
course2.addStudent(student2);
System.out.println("Students enrolled in " + course1.getName() + ":");
for (Student student : course1.getStudents()) {
System.out.println(student.getName());
}
System.out.println("Students enrolled in " + course2.getName() + ":");
for (Student student : course2.getStudents()) {
System.out.println(student.getName());
}
student1.enroll(course1);
student1.enroll(course2);
System.out.println("Courses enrolled by " + student1.getName() + ":");
for (Course course : student1.getCourses()) {
System.out.println(course.getName());
}
student1.drop(course1);
System.out.println("Courses enrolled by " + student1.getName() + " after dropping " + course1.getName() + ":");
for (Course course : student1.getCourses()) {
System.out.println(course.getName());
}
course1.removeStudent(student1);
System.out.println("Students enrolled in " + course1.getName() + " after removing " + student1.getName() + ":");
for (Student student : course1.getStudents()) {
System.out.println(student.getName());
}
}
}
```
以上程序可以实现学生选课系统的基本功能,包括课程的添加和删除、学生的选课和退选等。如果您有任何疑问,请随时与我进行交流。
阅读全文