自定义二叉搜索树(Roster)中按课程打印学生的实现问题
我来帮你一步步解决这个问题,看起来你卡在了两个关键点上:printCourse方法的逻辑实现,以及它和displayStudent方法之间的调用问题。咱们先理清思路,再给出具体的代码方案。
问题拆解与解决思路
首先,核心需求是遍历整个二叉搜索树(Roster),找出所有修读特定课程的学生,然后调用displayStudent打印他们的信息。这里可能的问题有两个:
printCourse没有正确遍历二叉搜索树,或者没有正确检查学生的课程链表- 方法的访问权限或调用逻辑不对,导致无法从
printCourse里调用displayStudent
具体代码实现示例
1. 先调整Student类,增加课程检查方法
首先给Student类加一个判断是否修读目标课程的辅助方法,这样printCourse可以快速验证学生是否符合条件:
public class Student { private String id; private CourseNode courseHead; // 课程链表节点内部类 private class CourseNode { String courseName; double grade; CourseNode next; CourseNode(String name, double grade) { this.courseName = name; this.grade = grade; this.next = null; } } // 构造方法、添加课程的方法这里省略,你应该已经实现了 // 判断当前学生是否修读目标课程 public boolean takesCourse(String targetCourse) { CourseNode current = courseHead; while (current != null) { if (current.courseName.equalsIgnoreCase(targetCourse)) { // 忽略大小写可选 return true; } current = current.next; } return false; } // 打印单个学生信息的方法(如果这个方法在Student类里) public void displayStudent() { System.out.println("Student ID: " + this.id); System.out.println("Enrolled Courses:"); CourseNode current = courseHead; while (current != null) { System.out.printf(" - %s: %.2f%n", current.courseName, current.grade); current = current.next; } System.out.println("------------------------"); } }
2. 修复Roster类中的printCourse方法
接下来在Roster类里实现正确的printCourse方法,确保它能遍历整个二叉搜索树,并且调用displayStudent:
public class Roster { private Node root; // 二叉搜索树节点内部类 private class Node { Student student; Node left; Node right; Node(Student student) { this.student = student; this.left = null; this.right = null; } } // 插入节点的方法这里省略,你应该已经实现了 // 对外暴露的打印特定课程学生的方法 public void printCourse(String targetCourse) { System.out.printf("Students enrolled in %s:%n", targetCourse); // 递归遍历整个二叉搜索树 traverseAndPrint(root, targetCourse); } // 递归遍历辅助方法 private void traverseAndPrint(Node currentNode, String targetCourse) { if (currentNode == null) { return; } // 中序遍历(保证按ID顺序输出,符合BST特性) traverseAndPrint(currentNode.left, targetCourse); // 检查当前学生是否修读目标课程,是则打印 Student student = currentNode.student; if (student.takesCourse(targetCourse)) { // 如果displayStudent在Student类里,直接通过对象调用 student.displayStudent(); // 如果displayStudent是Roster类的方法,就改成:this.displayStudent(student); } traverseAndPrint(currentNode.right, targetCourse); } // 如果你把displayStudent放在Roster类里,方法应该是这样的: /* public void displayStudent(Student student) { System.out.println("Student ID: " + student.getId()); // 打印课程逻辑... } */ }
关键问题排查点
如果还是无法调用displayStudent,你可以检查这几点:
- 访问权限:如果
displayStudent是private,要确保它和printCourse在同一个类里(比如都在Roster类);如果在Student类里,要改成public才能被外部调用。 - 调用方式:如果
displayStudent是Student类的方法,必须通过Student对象调用(student.displayStudent());如果是Roster类的方法,要传入Student对象作为参数。 - 遍历逻辑:之前的
printCourse可能没有完整遍历二叉搜索树(比如漏了左/右子树的递归),导致部分学生没被检查到。
内容的提问来源于stack exchange,提问作者Devin
相关产品推荐
相关产品推荐

