,java"/>

首页 > 解决方案 > Java:从 HashMap 打印内容

问题描述

我需要打印HashMap<String, StudentSchedule>StudentSchedule 是存储其他对象的类的所有内容。在 StudentSchedule 中,有一个函数可以打印出一些我希望它在打印 HashMap 时打印的数据。我已经使用增强的 for 循环来打印 HashMap,但是值就像对象编号。当值正在打印时,我希望它打印 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]);
        }
    }
}

调度管理器

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());
        }

    }
....

标签: java

解决方案


覆盖toStringStudentSchedule 类的方法并在其中调用 printSchedule。像这样的东西

@Override
public String toString() { 
    printSchedule();
    return ""; 
} 

推荐阅读