Java医院管理系统:如何让Hospital类的seeStaff方法正确打印员工列表
问题原因与解决办法
核心原因
- 对象实例不统一:你在
main中创建并添加员工的是HospitalStaff hs实例,但Hospital类的seeStaff方法里又新建了一个空的HospitalStaff hs1。这两个是完全独立的对象,新实例的listofStaff没有任何员工数据,遍历自然无输出。 - 未触发打印逻辑:
main方法里没有调用Hospital类的seeStaff方法,即便逻辑正确,也不会执行打印操作。
解决步骤
步骤1:让Hospital持有共享的HospitalStaff实例
给Hospital类添加一个HospitalStaff类型的成员变量,通过构造方法传入已初始化的员工实例,确保操作的是同一个对象。
步骤2:修正seeStaff方法逻辑
在seeStaff方法中使用共享的HospitalStaff实例,而非每次新建空对象。
步骤3:在main中调用打印方法
添加调用h.seeStaff()的代码,触发员工列表打印。
修改后的完整代码
import java.util.ArrayList; import java.util.List; public class HospitalProject { public static void main(String[] args) { HospitalStaff hs = new HospitalStaff(); hs.addHospitalStaff("A103", "Name1", "Lastname1", "Surgery", "Doctor"); hs.addHospitalStaff("A124", "Name2", "Lastname2", "Surgery", "Doctor"); // 将已添加员工的HospitalStaff实例传给Hospital Hospital h = new Hospital(hs); h.Hospitalinformation(); // 调用打印员工方法 h.seeStaff(); } } class Hospital{ public String name = "Red Cross"; public String Address = "whatever"; public String phonenum = "whatever2"; private String email = "whatever@gmail.com"; // 持有共享的HospitalStaff实例 private HospitalStaff hospitalStaff; // 通过构造方法传入HospitalStaff实例 public Hospital(HospitalStaff hospitalStaff) { this.hospitalStaff = hospitalStaff; } public void Hospitalinformation() { System.out.println("The name of the hospital is: " +name + " \nThe name of the Address: " + Address + "\nPhone number: "+phonenum + " \nEmail Address: " + email); } public void seeStaff() { // 使用共享的实例遍历员工列表 for(String staff : hospitalStaff.listofStaff) { System.out.println(staff); } } } class HospitalStaff { private String StaffId; public String firstname; public String lastname; public String department; public String stafftype; List<String> listofStaff = new ArrayList<String>(); public void addHospitalStaff(String StaffId, String firstname, String lastname, String department, String stafftype) { String here = StafftoString(StaffId, firstname, lastname, department, stafftype); listofStaff.add(here); } public String StafftoString(String StaffId, String firstname, String lastname, String department, String stafftype) { return firstname + " " + lastname + " " + StaffId + " " + department + " " + stafftype; } public void seeStaff() { for(String stafflist: listofStaff) { System.out.println(stafflist); } } }
额外优化建议
- 把
HospitalStaff的listofStaff改成私有成员,通过公共方法获取员工列表(比如添加public List<String> getStaffList()方法),遵循封装原则。 - 方法名遵循Java驼峰命名规范,比如
Hospitalinformation改为printHospitalInformation,seeStaff改为printAllStaff。
内容的提问来源于stack exchange,提问作者ABC123
相关产品推荐
相关产品推荐

