package Demo03;
class User{
private String userid;
private String name;
private UserCourse[] ucs;
public void setUcs(UserCourse[] ucs){
this.ucs = ucs;
}
public UserCourse[] getUcs(){
return this.ucs;
}
public User(String userid,String name){
this.userid = userid;
this.name = name;
}
public String getUserInfo(){
return "用户编号:"+this.userid+",姓名:"+this.name;
}
}
class Course{
private int cid;
private String title;
private int num;
private String note;
private UserCourse[] ucs;
public void setUcs(UserCourse[] ucs){
this.ucs = ucs;
}
public UserCourse[] getUcs(){
return this.ucs;
}
public Course(int cid,String title,int num,String note){
this.cid = cid;
this.title = title;
this.num = num;
this.note = note;
}
public String getCourseInfo(){
return "课程编号:"+this.cid+"名称:"+this.title+",课时:"+this.num+",简介:"+this.note;
}
}
class UserCourse{
private User user;
private Course course;
private String note;
private double score;
public UserCourse(User user,Course course,String note,double score){
this.user = user;
this.course = course;
this. note = note;
this.score = score;
}
public double getScore(){
return this.score;
}
public Course getCourse(){
return this.course;
}
public User getUser(){
return this.user;
}
}
public class TestDemo02 {
public static void main(String[] args) {
//第一步:设置类与类之间的关系
//1、定义单独的类对象
User ua = new User("zhangsan","张三");
User ub = new User("lisi","李四");
User uc = new User("wangwu","王五");
Course c1 = new Course(1,"Orcle",50,"-");
Course c2 = new Course(2,"Java",300,"-");
//2、设置彼此的关系
UserCourse uca = new UserCourse(ua,c1,"暂无评价",90.0);
UserCourse ucb = new UserCourse(ua,c2,"暂无评价",89.0);
UserCourse ucc = new UserCourse(ub,c1,"暂无评价",70.0);
UserCourse ucd = new UserCourse(uc,c1,"暂无评价",77.0);
UserCourse uce = new UserCourse(uc,c2,"暂无评价",79.0);
//3、在用户中设置关系
ua.setUcs(new UserCourse[]{uca,ucb});
ub.setUcs(new UserCourse[]{ucc});
uc.setUcs(new UserCourse[]{ucd,uce});
c1.setUcs(new UserCourse[]{uca,ucc,ucd});
c2.setUcs(new UserCourse[]{ucb,uce});
//第二步:取得信息
System.out.println(c1.getCourseInfo());//输出一个课程信息
for(int x = 0;x<c1.getUcs().length;x++){//该门课程的用户信息
System.out.println("\t|-"+c1.getUcs()[x].getUser().getUserInfo()+",成绩:"+c1.getUcs()[x].getScore());
}
System.out.println("\n=========================================\n");
//用户ua所学的所有课程
System.out.println(ua.getUserInfo());
for (int x = 0;x<ua.getUcs().length;x++){
System.out.println(ua.getUcs()[x].getCourse().getCourseInfo()+",考试成绩:"+ua.getUcs()[x].getScore());
}
}
}
Java双向一对多的映射(用户-课程-用户参加课程)
最新推荐文章于 2024-06-09 16:06:06 发布