在java中,如何在主类中没有循环的情况下在数组中保存4个医生姓名和专业?不是班博士。 伪代码:
public class Doctor
{
private String name = ""; // set the name default is null
private String specialisation = ""; // // set the specialisation default is null
public void setName(String name) { // this one is save the name of the doctor
this.name = name;
}
public void setSpecialisation(String specialisation) { // // this one is save the specialisation of the doctor
this.specialisation = specialisation;
}
public String getSpecialisation() // this function to get data to show what specialisation of doctor
{
return specialisation;
}
public String getName() // // this function to get data to show what is the name of the doctor
{
return name;
}
}
答案 0 :(得分:0)
您可以使用数组保存多个医生:
// Create an empty array
List<Doctor> doctors = new ArrayList();
// Create instance of Doctor class
Doctor d1 = new Doctor();
// Setname here
d1.setName("Name1");
// set Specialisation here
d1.setSpecialisation("Specialisation1");
// Add this object to array
doctors.add(d1);
Doctor d2 = new Doctor();
d2.setName("Name2");
d2.setSpecialisation("Specialisation2");
doctors.add(d2);
//...similarly for other doctros
System.out.println(doctors.size());
如果你想从菜单中使用它,请创建一个函数,如:
class AddDoctor {
List<Doctor> doctors = new ArrayList();
private void addDoctor(String name, String specialisation) {
// Check already exists
if(checkAlreadyExists(name)) {
System.out.println("Already exists witht this name")
}
// Create instance of Doctor class
Doctor d = new Doctor();
// Setname here
d.setName(name);
// set Specialisation here
d.setSpecialisation(specialisation);
// Add this object to array
doctors.add(d);
}
}
private boolen checkAlreadyExists(String name) {
for(Doctor d : doctors) {
if(d.getName().equals(name)) {
return true;
}
}
return false;
}
接受用户输入(姓名和专业)并从菜单中调用此方法,例如:
addDoctor("Name1", "specialisation1");