学生选课系统:一个学生可以选择多门课程,一门课程也可以被很多学生选择,学生和课程之间是多对多的关系。
首先我们先封装一个学生类,里面有学生的姓名、年龄等属性,还有盛放课程的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());
}
}
}
运行结果: