如何编写返回更新后ArrayList的Java方法实现医生信息录入功能
Java 抽取添加Doctor逻辑到独立方法解决方案
原有代码问题
- 方法签名中的泛型未指定具体类型,不符合Java语法规范
- 方法内部重新创建
ArrayList<Doctor>实例,会清空原有列表中的历史数据 - 重复创建
Scanner对象,多次调用易引发输入流冲突 - 存在拼写错误:
Arraylist应为ArrayList,Java大小写敏感
修正后的方法实现
public static ArrayList<Doctor> addDoctorToList(ArrayList<Doctor> originalDoctors, Scanner scanner) { System.out.println("What is the name of the doctor?"); String nameDoctor = scanner.nextLine(); System.out.println("What is the doctor's specialisation?"); String specialisationDoctor = scanner.nextLine(); originalDoctors.add(new Doctor(nameDoctor, specialisationDoctor)); System.out.println("added!"); return originalDoctors; }
主方法调用方式
替换原有选项1的逻辑块即可:
if (option.equals("1")) { listOfDoctors = addDoctorToList(listOfDoctors, scanner); }
说明
因为ArrayList是引用类型,如果你不需要方法返回值也可以去掉返回声明,方法内部对传入的列表修改会直接同步到主方法的原列表对象,上述返回的写法更贴合你需要返回更新后列表的需求。
内容的提问来源于stack exchange,提问作者Quincy van Deursen
相关产品推荐
相关产品推荐

