學生選課系統:一個學生可以選擇多門課程,一門課程也可以被很多學生選擇,學生和課程之間是多對多的關系。
首先我們先封裝一個學生類,里面有學生的姓名、年齡等屬性,還有盛放課程的List集合。
然后封裝一個課程類,有課程名稱,學分還有盛放學生的List集合。
最后是一個測試類,在測試類里實例化學生和課程進行測試。



代碼如下:

學生類:

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("應用密碼學",2.0f);
  Course c2=new Course("中小型網絡組建",5.0f);
  Course c3=new Course("數字水印",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("學生姓名:"+stu1.getName());
  Iterator<Course> iter1=stu1.getCourseList().iterator();
  while(iter1.hasNext()){
   Course c=iter1.next();
   System.out.println("\t| 課程名稱:"+c.getName()+",學分: "+c.getScore());
  }
  System.out.println("課程名稱:"+c3.getName());
  Iterator<Student> iter2=c3.getStudentList().iterator();
  while(iter2.hasNext()){
   Student s=iter2.next();
   System.out.println("\t| 學生姓名:"+s.getName()+",學生年齡:"+s.getAge());
  }
  
 }

}

運行結果: