學(xué)生選課系統(tǒng):一個學(xué)生可以選擇多門課程,一門課程也可以被很多學(xué)生選擇,學(xué)生和課程之間是多對多的關(guān)系。
首先我們先封裝一個學(xué)生類,里面有學(xué)生的姓名、年齡等屬性,還有盛放課程的List集合。
然后封裝一個課程類,有課程名稱,學(xué)分還有盛放學(xué)生的List集合。
最后是一個測試類,在測試類里實(shí)例化學(xué)生和課程進(jìn)行測試。
代碼如下:
學(xué)生類:
package com.dr.selectcourse;
import java.util.ArrayList;
import java.util.List;
public class Student {
private String name;
private int age;
private List<Course> CourseList;
public Student(String name,int age){
this.setName(name);
this.setAge(age);
this.setCourseList(new ArrayList<Course>());
}
public void addCourse(Course course){
this.CourseList.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> getCourseList() {
return CourseList;
}
public void setCourseList(List<Course> courseList) {
this.CourseList = courseList;
}
}
課程類:
package com.dr.selectcourse;
import java.util.ArrayList;
import java.util.List;
public class Course {
private String name;
private float score;
private List<Student> StudentList;
public Course(String name,float score){
this.setName(name);
this.setScore(score);
this.setStudentList(new ArrayList<Student>());
}
public void addStudent(Student student){
this.StudentList.add(student);
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public float getScore() {
return score;
}
public void setScore(float score) {
this.score = score;
}
public List<Student> getStudentList() {
return StudentList;
}
public void setStudentList(List<Student> studentList) {
this.StudentList = studentList;
}
}
測試類
package com.dr.selectcourse;
import java.util.Iterator;
import java.util.List;
public class SelectCourse {
public static void main(String[] args) {
Course c1=new Course("應(yīng)用密碼學(xué)",2.0f);
Course c2=new Course("中小型網(wǎng)絡(luò)組建",5.0f);
Course c3=new Course("數(shù)字水印",2.0f);
Student stu1=new Student("宋可",20);
Student stu2=new Student("田馨",21);
Student stu3=new Student("林嵐",21);
Student stu4=new Student("劉昕",22);
Student stu5=new Student("張涵",21);
c1.addStudent(stu1);
stu1.addCourse(c1);
c2.addStudent(stu2);
stu2.addCourse(c2);
c3.addStudent(stu3);
stu3.addCourse(c3);
c1.addStudent(stu4);
stu4.addCourse(c1);
c3.addStudent(stu5);
stu5.addCourse(c3);
System.out.println("學(xué)生姓名:"+stu1.getName());
Iterator<Course> iter1=stu1.getCourseList().iterator();
while(iter1.hasNext()){
Course c=iter1.next();
System.out.println("\t| 課程名稱:"+c.getName()+",學(xué)分: "+c.getScore());
}
System.out.println("課程名稱:"+c3.getName());
Iterator<Student> iter2=c3.getStudentList().iterator();
while(iter2.hasNext()){
Student s=iter2.next();
System.out.println("\t| 學(xué)生姓名:"+s.getName()+",學(xué)生年齡:"+s.getAge());
}
}
}
運(yùn)行結(jié)果: