用java集合做一个教务系统
时间: 2023-10-12 22:07:34 浏览: 45
好的,我可以为您提供一个简单的教务系统的Java代码示例,其中使用了Java集合。
首先,让我们定义一个学生类,它包含学生的名称、学号、课程列表等信息。
```java
public class Student {
private String name;
private int id;
private List<Course> courses;
public Student(String name, int id) {
this.name = name;
this.id = id;
courses = new ArrayList<>();
}
public void addCourse(Course course) {
courses.add(course);
}
// Getters and setters for name, id, and courses
}
```
接下来,让我们定义课程类,它包含课程名称、教师名称、成绩等信息。
```java
public class Course {
private String name;
private String teacher;
private int grade;
public Course(String name, String teacher) {
this.name = name;
this.teacher = teacher;
grade = 0;
}
public void setGrade(int grade) {
this.grade = grade;
}
// Getters for name, teacher, and grade
}
```
现在,我们可以创建一个教务系统类,其中包含学生和课程的列表,以及添加学生和课程,给学生添加课程和设置学生成绩等功能。
```java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class EducationSystem {
private Map<Integer, Student> students;
private List<Course> courses;
public EducationSystem() {
students = new HashMap<>();
courses = new ArrayList<>();
}
public void addStudent(Student student) {
students.put(student.getId(), student);
}
public void addCourse(Course course) {
courses.add(course);
}
public void enrollStudent(int studentId, String courseName) {
Student student = students.get(studentId);
Course course = findCourse(courseName);
if (student != null && course != null) {
student.addCourse(course);
}
}
public void setGrade(int studentId, String courseName, int grade) {
Student student = students.get(studentId);
Course course = findCourse(courseName);
if (student != null && course != null) {
course.setGrade(grade);
}
}
private Course findCourse(String courseName) {
for (Course course : courses) {
if (course.getName().equals(courseName)) {
return course;
}
}
return null;
}
}
```
现在,我们可以使用这个教务系统类来创建学生和课程,并将学生注册到课程中,设置学生成绩等。
```java
public class Main {
public static void main(String[] args) {
EducationSystem system = new EducationSystem();
// Create some students
Student alice = new Student("Alice", 1001);
Student bob = new Student("Bob", 1002);
// Add students to the system
system.addStudent(alice);
system.addStudent(bob);
// Create some courses
Course math = new Course("Math", "Mr. Smith");
Course english = new Course("English", "Ms. Johnson");
// Add courses to the system
system.addCourse(math);
system.addCourse(english);
// Enroll students in courses
system.enrollStudent(1001, "Math");
system.enrollStudent(1001, "English");
system.enrollStudent(1002, "Math");
// Set grades for students
system.setGrade(1001, "Math", 90);
system.setGrade(1001, "English", 85);
system.setGrade(1002, "Math", 80);
}
}
```
这就是一个简单的教务系统的Java代码示例,其中使用了Java集合。当然,这只是一个基本的原型,您可以根据需要进行更多的扩展和改进。