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

Java如何将文本文件内容读取到存储对象的ArrayList中

代码存在的问题如下
  • Scanner对象使用错误
    读取Appointment.txt时你声明了名为sc的Scanner对象,但第二个while循环的判断条件仍然使用已经读完Citizen.txt的s.hasNext(),循环内部读取行也用的是s.nextLine(),完全没有用到指向Appointment.txt的sc对象,会直接抛出NoSuchElementException,或者根本不会进入循环读取内容。
  • LocalDateTime解析未指定格式化器
    你已经定义了匹配格式的DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm"),但调用LocalDateTime.parse()时没有传入这个格式化器,默认格式和你的文本格式不匹配,会抛出DateTimeParseException。
  • check方法逻辑完全错误
    现有check方法的判断条件为if(d.equals(d.getNumber())),是将CitizenData对象和自身的numberID字符串做相等判断,永远返回false,方法最终只会返回null,后续使用null对象会触发空指针异常。正确逻辑应该是判断传入的参数x和CitizenData的numberID是否相等。
  • 异常排查不便
    当前catch块只打印固定提示,看不到具体错误原因,建议添加堆栈打印,可快速定位具体异常类型和出错位置。

修正后的核心代码
public static void read(){
    try{
        Scanner s = new Scanner(new File("Citizen.txt"));
        DateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
        while(s.hasNext()){
            String fullName = s.nextLine();
            String numberID = s.nextLine();
            int age = Integer.parseInt(s.nextLine());
            Date date = formatter.parse(s.nextLine());
            String address = s.nextLine();
            String phoneNum = s.nextLine();
            String email = s.nextLine();
            s.nextLine();
            CitizenData data = new CitizenData(fullName,numberID,age,date,address,phoneNum,email);
            citizenData.add(data);
        }
        s.close();
        Scanner sc = new Scanner(new File("Appointment.txt"));
        DateTimeFormatter dtf = DateTimeFormatter.ofPattern("dd-MMM-yyyy HH:mm");
        // 改用sc判断是否有剩余内容
        while(sc.hasNext()){
            CitizenData numberID = DataIO.check(sc.nextLine());
            VaccinationCentre vacCentre = VaccinationCentre.valueOf(sc.nextLine());
            // 解析时传入自定义格式化器
            LocalDateTime date = LocalDateTime.parse(sc.nextLine(), dtf);
            String vaccineType = sc.nextLine();
            sc.nextLine();
            AppointmentData data1 = new AppointmentData(numberID, vacCentre, date,vaccineType);
            appointment.add(data1);
        }
        sc.close();
    }catch(Exception e){
        System.out.println("Error in read");
        e.printStackTrace();// 新增堆栈打印方便排查
    }
}

public static CitizenData check(String x){
    for(CitizenData d : citizenData){
        // 修正判断逻辑,对比传入的ID和对象存储的ID
        if(d.getNumber().equals(x)){
            return d;
        }
    }
    return null;
}

内容的提问来源于stack exchange,提问作者user16916070

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 11:24:05