You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何编写返回更新后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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 04:45:02