课程类
public class Course {
private String name;
private int score;
private List<Student> students;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getScore() {
return score;
}
public void setScore(int score) {
this.score = score;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
public Course() {
super();
// TODO Auto-generated constructor stub
students = new ArrayList<Student>();
}
public Course(String name, int score) {
this();
this.name = name;
this.score = score;
}
@Override
public String toString() {
return "Course [name=" + name + ", score=" + score ;
}
public void showInfo(){
System.out.println("课程名称:"+name+",课程学分:"+score);
if(students.size()==0){
System.out.println("\t此课程尚未有学生选修");
return ;
}
//遍历
int no =1;
Iterator<Student> it=students.iterator();
while(it.hasNext()){
Student s=it.next();
System.out.println("\t"+(no++)+",学生姓名:"+s.getName()+",学生年龄:"+s.getAge());
}
}
}
学生类
public class Student {
private String name;
private int age;
private List<Course> courses;
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> getCourses() {
return courses;
}
public void setCourses(List<Course> courses) {
this.courses = courses;
}
public Student() {
super();
// TODO Auto-generated constructor stub
courses = new ArrayList<Course>();
}
public Student(String name, int age) {
this();
this.name = name;
this.age = age;
}
public void showInfo(){
System.out.println("=================华丽丽的分隔线=================");
System.out.println("学生姓名:"+name+",年龄:"+age);
if(courses.size()==0){
System.out.println("\t该生尚未选课");
}else{
int no = 1;
for(Course c:courses){
System.out.println("\t"+(no++)+"\t课程名称:"+c.getName()+"\t课程学分:"+c.getScore());
}
}
}
}
测试类
public static void chooseCourse(Student s,Course c){
s.getCourses().add(c);
c.getStudents().add(s);
}
public static void main(String[] args) {
Student s1 = new Student("张三", 20);
Student s2 = new Student("李四", 20);
Student s3 = new Student("王五", 20);
Student s4 = new Student("赵六", 20);
Course c1=new Course("高等数学", 5);
Course c2=new Course("线性代数", 3);
Course c3=new Course("离散数学", 5);
Course c4=new Course("概率论", 4);
chooseCourse(s1, c1);
chooseCourse(s1, c2);
chooseCourse(s1, c3);
chooseCourse(s2, c1);
chooseCourse(s2, c2);
chooseCourse(s2, c4);
s1.showInfo();
s2.showInfo();
c1.showInfo();
c2.showInfo();
}
}