我需要打印HashMap<String, StudentSchedule>
中的所有内容,其中StudentSchedule是存储其他对象的类。在StudentSchedule中,有一个函数可以打印出一些我希望在打印HashMap时要打印的数据。我使用了增强的for循环来打印HashMap,但是这些值类似于对象Number。当值正在打印时,我希望它打印出StudentSchedule.printSchedule()中的函数。我不确定这是否可能。我想我已经使它变得更复杂了,但是到目前为止,这是我所要做的:
public class StudentSchedule {
private Student student;
private Course course;
private String[] courseDays;
private String[] courseTimes;
public StudentSchedule(Student student, Course course, String[] courseDays, String[] courseTimes) {
this.student = student;
this.course = course;
this.courseDays = courseDays;
this.courseTimes = courseTimes;
}
public Student getStudent() {
return student;
}
public Course getCourse() {
return course;
}
public String[] getCourseDays() {
return courseDays;
}
public String[] getCourseTimes() {
return courseTimes;
}
public void printSchedule() {
System.out.println("\nClass Schedule");
String studentInfo = getStudent().toString();
String courseInfo = getCourse().toString();
String[] courseDays = getCourseDays();
String[] courseTimes = getCourseTimes();
if(courseDays[2] != null && courseTimes[2] != null) {
System.out.println(studentInfo + "\n" + courseInfo + "\n" +
courseDays[0] + " -> " + courseTimes[0] + "\n" +
courseDays[1] + " -> " + courseTimes[1] + "\n" +
courseDays[2] + " -> " + courseTimes[2]);
}
else {
System.out.println(studentInfo + "\n" + courseInfo + "\n" +
courseDays[0] + " -> " + courseTimes[0] + "\n" +
courseDays[1] + " -> " + courseTimes[1]);
}
}
}
ScheduleManager
public class ScheduleManager
{
private HashMap<String, StudentSchedule> allStudentSchedule = new HashMap<>();
public void createSchedule() {
Student newStudent = getStudentInfo();
Course newCourse = getCourseInfo();
courseDays = getCourseDays();
courseTimes = getCourseTimes(courseDays);
studentSchedule = new StudentSchedule(newStudent, newCourse, courseDays, courseTimes);
allStudentSchedule.put(newStudent.getStudentId(), studentSchedule);
// testing print schedule
studentSchedule.printSchedule();
}
private void displaySchedule() {
Set<Entry<String,StudentSchedule>> hashSet = allStudentSchedule.entrySet();
for(Entry entry : hashSet ) {
System.out.println("Key="+entry.getKey()+", Value="+entry.getValue());
}
}
....
答案 0 :(得分:0)
覆盖StudentSchedule类的toString
方法,并在其中调用printSchedule。像这样
@Override
public String toString() {
printSchedule();
return "";
}