前提要点分析:
学生与课程之间的关系就是:
一个课程对应多个学生,一个学生对应多个课程。
本代码做的就是:将每个课程对应的学生 以及 每个学生对应的课程 关联起来。
public class Course { int number;// 课程号 String name;// 课程名称 private Student[] classList; int StudentCount;// 学生人数 Course(String name, int id) { this.number = id; this.name = name; StudentCount = 0; classList = new Student[10]; } public Student[] getClassList() { return classList; } public int getStudentCount() { return StudentCount; } public int getNumber() { return number; } public String getName() { return name; } public void addStudent(Student s) { classList[StudentCount++] = s; } }
public class Student { public String name; public int number; private Course[] courseList; public int courseCount; public Student(int number,String name) { this.number = number; this.name = name; courseCount =0; courseList = new Course[10]; } public void addCourse(Course c) { courseList[courseCount++]=c; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getNumber() { return number; } public void setNumber(int number) { this.number = number; } public Course[] getCourseList() { return courseList; } public void setCourseList(Course[] courseList) { this.courseList = courseList; } public int getCourseCount() { return courseCount; } public void setCourseCount(int courseCount) { this.courseCount = courseCount; } }
public class Test { public static void main(String[] args) { Course c1 = new Course("语文", 1); Course c2 = new Course("数学", 2); Course c3 = new Course("英语", 3); Student s1 = new Student(21072134, "张三"); Student s2 = new Student(20172135, "李四"); s1.addCourse(c1); s1.addCourse(c3); s2.addCourse(c3); s2.addCourse(c2); c1.addStudent(s1); c2.addStudent(s2); c3.addStudent(s2); c3.addStudent(s1); System.out.println("课程"+c1.number+c1.name+"的学生数:"+c1.getStudentCount()); System.out.println("课程"+c2.number+c2.name+"的学生数:"+c2.getStudentCount()); System.out.println("课程"+c3.number+c3.name+"的学生数:"+c3.getStudentCount()); System.out.println(s1.number+s1.name+"的课程数:"+s1.getCourseCount()); System.out.println(s2.number+s2.name+"的课程数:"+s2.getCourseCount()); } }