java学生选课系统代码
时间: 2023-08-10 16:05:01 浏览: 49
以下是一个简单的Java学生选课系统代码,代码中包含了学生类和课程类,以及一个选课系统类,可以实现学生选课和退课的功能。
```java
import java.util.ArrayList;
class Student {
private String name;
private ArrayList<Course> courses;
public Student(String name) {
this.name = name;
courses = new ArrayList<Course>();
}
public String getName() {
return name;
}
public void addCourse(Course course) {
courses.add(course);
}
public void removeCourse(Course course) {
courses.remove(course);
}
public ArrayList<Course> getCourses() {
return courses;
}
}
class Course {
private String name;
private int credit;
public Course(String name, int credit) {
this.name = name;
this.credit = credit;
}
public String getName() {
return name;
}
public int getCredit() {
return credit;
}
}
public class CourseSelectionSystem {
private ArrayList<Student> students;
private ArrayList<Course> courses;
public CourseSelectionSystem() {
students = new ArrayList<Student>();
courses = new ArrayList<Course>();
}
public void addStudent(Student student) {
students.add(student);
}
public void removeStudent(Student student) {
students.remove(student);
}
public void addCourse(Course course) {
courses.add(course);
}
public void removeCourse(Course course) {
courses.remove(course);
}
public ArrayList<Student> getStudents() {
return students;
}
public ArrayList<Course> getCourses() {
return courses;
}
public void enroll(Student student, Course course) {
student.addCourse(course);
}
public void drop(Student student, Course course) {
student.removeCourse(course);
}
}
```
使用示例:
```java
public static void main(String[] args) {
// 创建选课系统
CourseSelectionSystem css = new CourseSelectionSystem();
// 创建学生
Student alice = new Student("Alice");
Student bob = new Student("Bob");
// 创建课程
Course math = new Course("Math", 3);
Course cs = new Course("Computer Science", 4);
Course history = new Course("History", 2);
// 添加学生和课程到选课系统
css.addStudent(alice);
css.addStudent(bob);
css.addCourse(math);
css.addCourse(cs);
css.addCourse(history);
// 学生选课
css.enroll(alice, math);
css.enroll(alice, cs);
css.enroll(bob, math);
css.enroll(bob, history);
// 输出学生选课情况
ArrayList<Student> students = css.getStudents();
for (Student student : students) {
System.out.println(student.getName() + ":");
ArrayList<Course> courses = student.getCourses();
for (Course course : courses) {
System.out.println("- " + course.getName() + " (" + course.getCredit() + " credits)");
}
}
// 学生退课
css.drop(alice, math);
// 输出学生选课情况
students = css.getStudents();
for (Student student : students) {
System.out.println(student.getName() + ":");
ArrayList<Course> courses = student.getCourses();
for (Course course : courses) {
System.out.println("- " + course.getName() + " (" + course.getCredit() + " credits)");
}
}
}
```
输出结果:
```
Alice:
- Math (3 credits)
- Computer Science (4 credits)
Bob:
- Math (3 credits)
- History (2 credits)
Alice:
- Computer Science (4 credits)
Bob:
- Math (3 credits)
- History (2 credits)
```