我正在用Java做一个医院管理系统项目。我有3个类。一个类有main方法,另一个类是Hospital类,它有打印医院详细信息的方法,还有一个方法打印医院的员工。第三个类是HospitalStaff类,它有一个toString方法,用于所有员工的详细信息。还有一个addStaff方法,员工被添加到一个数组列表中,我希望打印所有员工的方法,存在于Hospital类中,怎么做?
下面是我的代码:
import java.util.ArrayList;
import java.util.List;
public class HospitalProject {
public static void main(String[] args) {
Hospital h = new Hospital();
h.Hospitalinformation();
HospitalStaff hs = new HospitalStaff();
hs.addHospitalStaff("A103", "Name1", "Lastname1", "Surgery", "Doctor");
hs.addHospitalStaff("A124", "Name2", "Lastname2", "Surgery", "Doctor");
}
}
/* This is the Hospital class. It has 3 methods. The HospitalInformation method prints the name and the address, name, email address and phone number of the hospital.
* It declares and array list by the name of listofStaff of the type HospitalStaff.
* It consists of a seeStaff method which is supposed to show all staff working at the hospital.
*/
class Hospital{
public String name = "Red Cross";
public String Address = "whatever";
public String phonenum = "whatever2";
private String email = "whatever@gmail.com";
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() {
HospitalStaff hs1 = new HospitalStaff();
for(String stafflist: hs1.listofStaff) {
System.out.println(stafflist);
}
}
}
/*The Hospital Staff method consists of toString method as well as a addHospitalStaff method.
* The seeStaff method is added for debugging purposes, it is however, supposed to exist in the Hospital method.
*/
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 String.valueOf(firstname) + " " + String.valueOf(lastname) +" " + String.valueOf(StaffId) +" " + String.valueOf(department) +" " + String.valueOf(stafftype);
}
public void seeStaff() {
for(String stafflist: listofStaff) {
System.out.println(stafflist);
}
}
}
我尝试在Hospital类中创建一个名为seeStaff()的方法,并在该方法中创建了一个名为"hs1"的HospitalStaff对象。然后,我使用HospitalStaff对象调用HospitalStaff类中创建的数组列表(名为listofStaff)。我在for each循环中将其用作(String stafflist:hs1.listofStaff)。然而,当我在main中创建一个Hospital类对象并调用seeStaff()方法时,它没有打印任何内容。我不确定为什么会发生这种情况。
1条答案
按热度按时间vhipe2zx1#
在
seeStaff
方法中,您正在创建HospitalStaff
的一个新示例,该示例在创建时没有staff成员。因此,当您在该空示例中迭代staff成员列表时,不会得到输出。您在main()
中创建了HospitalStaff
的另一个示例,但不对该示例执行任何操作。解决这个问题的一种方法是先创建
HospitalStaff
示例,然后在创建Hospital
示例时,将HospitalStaff
示例传递给Hospital
的构造函数,以便将其存储在示例中,然后showStaff
方法可以打印HospitalStaff
示例中的值,如下所示:结果: