在这种情况下如何存储数组名称? (4名)

时间:2021-05-26 03:44:19

标签: java

在java中,如何在主类中没有循环的情况下在数组中保存4个医生姓名和专业?不是班博士。 伪代码:

  1. 主菜单(4 个选项)
  2. 按 1 是 AddDoctor
  3. 输入医生和专科医生的姓名(没有医生彼此同名)
  4. 该医生的正楷姓名和专科医生
  5. 返回主菜单
  6. 最多重做 4 次。 (如果足够 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;
            }
        }

1 个答案:

答案 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");