学生选课统计练习java

来源:互联网 发布:交易圣经知乎 编辑:程序博客网 时间:2024/05/01 18:22
package com.java;import java.util.HashMap;import java.util.HashSet;public class Test{public static void main(String[] args){Course english=new Course("英语");Course math=new Course("数学");Student lily=new Student("Lily");Student anan=new Student("Anan");lily.addCourse(english);lily.addCourse(math);anan.addCourse(english);//s2.removeCourse("英语");SchoolClass schoolClass=new SchoolClass();schoolClass.addStudent(lily);schoolClass.addStudent(anan);//schoolClass.removeStudent("Anan");HashMap<String, Integer> mapAccount = schoolClass.mapAccount();for(HashMap.Entry<String,Integer> e : mapAccount.entrySet()){System.out.println(e.getKey()+" : "+e.getValue());}}}class Course{private String name;public Course(String name){this.name=name;}public Course(){}public String getName(){return name;}public void setName(String name){this.name = name;}}class Student{private String name;private HashSet<Course> courseSet;public Student(){super();this.courseSet=new HashSet<Course>();}public Student(String name){super();this.name = name;this.courseSet=new HashSet<Course>();}public String getName(){return name;}public void setName(String name){this.name = name;}public HashSet<Course> getCourseSet(){return courseSet;}public void setCourseSet(HashSet<Course> courseSet){this.courseSet = courseSet;}public void  addCourse(Course c){this.courseSet.add(c);}public void removeCourse(String name){for(Course c:this.courseSet){if(c.getName().equals(name))this.courseSet.remove(c);}}}class SchoolClass{private HashSet<Student> studentSet;public SchoolClass(){super();studentSet=new HashSet<Student>();}public HashSet<Student> getStudentSet(){return studentSet;}public void setStudentSet(HashSet<Student> studentSet){this.studentSet = studentSet;}public void addStudent(Student s){studentSet.add(s);}public void removeStudent(String name){for(Student s:this.studentSet){if(s.getName().equals(name))this.studentSet.remove(s);}}public HashMap<String, Integer> mapAccount(){HashMap<String, Integer> resultMap=new HashMap<String,Integer>();for(Student s:this.studentSet){HashSet<Course> courseSet = s.getCourseSet();for(Course c:courseSet){Integer value = resultMap.get(c.getName());resultMap.put(c.getName(), value==null?1:++value);}}return resultMap;}}

原创粉丝点击