java - 在这种情况下如何存储数组名称?(4名)
问题描述
在java中,如何在我的主类中没有循环的情况下将4个医生姓名和专业保存在一个数组中?不是班博士。伪代码:
- 主菜单(4 个选项)
- PRESS 1 是 AddDoctor
- 输入医生姓名和专科医生姓名(没有医生姓名相同)
- 该医生的正楷姓名和专科医生
- 返回主菜单
- 最多重做 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;
}
}
解决方案
您可以使用数组保存多个医生:
// 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");
推荐阅读
- amazon-web-services - AWS Terraform cloudwatch - 从列表中读取的仪表板正文
- r - 当大小已经由另一个变量确定时,ggplot 使默认点大小变大
- laravel - 错误非法长度修饰符在 s[np]printf Laravel 中指定了 'f'
- php - 查找一个多维数组中的所有元素是否存在于另一个中(使用多维数组作为大海捞针)
- post - 如何在 esp32 中使用 shlib(nghttp2) 发送一大块数据?
- python - 在句子级别找到每个单词的频率
- c - 在 C 中生成大小为 10^6 的数组
- javascript - 是否可以不使用 Pine 脚本为交易视图编码?
- material-ui - MUI V5 - MakeStyles 样式被覆盖
- flutter - 有什么方法可以强类型地使用 Navigator?