首页 > 解决方案 > 在这种情况下如何存储数组名称?(4名)

问题描述

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

  1. 主菜单(4 个选项)
  2. PRESS 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;
            }
        }

标签: java

解决方案


您可以使用数组保存多个医生:

// 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");

推荐阅读