选课系统很有意思,学生选择一门课程以后,这门课程就会添加到这个学生的选课列表里面,同时这名学生也添加到了选择这门课程的学生列表里面,也就是学生和课程是双向选择的。
创建课程类Course,设置三个属性分别为名称、学分、学生名单。
Course
import java.util.ArrayList;
import java.util.List;
public class Course {
private String name;
private float grade;
private List<Student> allStudents;
public Course(String name,float grade){
this.setAllStudents(new ArrayList<Student>());
this.setGrade(grade);
this.setName(name);
}
public void addStu(Student student){
this.allStudents.add(student);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getGrade() {
return grade;
}
public void setGrade(float grade) {
this.grade = grade;
}
public List<Student> getAllStudents() {
return allStudents;
}
public void setAllStudents(List<Student> allStudents) {
this.allStudents = allStudents;
}
}
创建学生类Student,设置三个属性姓名、年龄、选课列表。
Student
import java.util.ArrayList;
import java.util.List;
public class Student {
private String name;
private int age;
private List<Course> allCourse;//一个学生可以选多门课
public Student(String name,int age){
this.setAge(age);
this.setAllCourse(new ArrayList<Course>());
this.setName(name);
}
public void addCourse(Course course){
this.allCourse.add(course);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public List<Course> getAllCourse() {
return allCourse;
}
public void setAllCourse(List<Course> allCourse) {
this.allCourse = allCourse;
}
}
创建测试类TestCourse,在里面创建五个学生三门课程,并对他们互相选择,并把每个学生选得课程添加到各自的选课列表,把选择每门课程的学生添加到各科的学生列表,然后进行遍历,学生的课程列表和课程的学生列表。
TestCourse
import java.util.Iterator;
public class TestCourse {
public static void main(String[] args) {
Student stu1 = new Student("张三",20);
Student stu2 = new Student("李四",21);
Student stu3 = new Student("王五",22);
Student stu4 = new Student("赵柳",23);
Student stu5 = new Student("孙琦",24);
Course c1 = new Course("Java se 基础",2.0f);
Course c2 = new Course("Java se web",3.0f);
Course c3 = new Course("分布式开发",5.0f);
// 设置关系
stu1.addCourse(c1);
c1.addStu(stu1);
stu1.addCourse(c2);
c2.addStu(stu1);
stu2.addCourse(c2);
c2.addStu(stu2);
stu3.addCourse(c1);
c1.addStu(stu3);
stu3.addCourse(c2);
c2.addStu(stu3);
stu3.addCourse(c3);
c3.addStu(stu3);
stu4.addCourse(c3);
c3.addStu(stu4);
stu5.addCourse(c3);
c3.addStu(stu5);
System.out.println("学生姓名:"+stu1.getName());
Iterator<Course> it1 = stu1.getAllCourse().iterator();
while(it1.hasNext()){
Course c = it1.next();
System.out.println("\t|-课程名称:"+c.getName()+",学分:"+c.getGrade());
}
System.out.println("课程名称:"+c3.getName());
Iterator<Student> it2 = c3.getAllStudents().iterator();
while(it2.hasNext()){
Student s = it2.next();
System.out.println("\t|-学生姓名:"+s.getName()+",年龄:"+s.getAge());
}
}
}
结果显示(只打印stu1和c1的列表)
posted on 2010-10-30 00:40
Mineralwasser 阅读(147)
评论(0) 编辑 收藏