首页 > 解决方案 > 将 CSV 文件读入链接列表 (Java)

问题描述

所以我无法读取 CSV 文件并将其添加到我的链接列表中。我已经将 csv 文件读入了诸如数组、arraylists 之类的东西,但从来没有读过单链表。现在我的问题是我在解析薪水的代码行上不断收到 ArrayOutOfBoundsException。该代码是我的菜单类的一部分,我在其中读取文件并将其添加到链接列表中。所以我的问题是,如何正确地将 csv 文件读入链表?谢谢!

public class EmpMenu {

private SLList<Employee> list = new SLList<Employee>();

public EmpMenu() {

    Scanner inFile = null;

    try {
        inFile = new Scanner(new File("employees.txt"));
    } catch (FileNotFoundException x) {
        System.err.print("File not found");
    }

    while (inFile.hasNextLine()) {
        String line = inFile.nextLine();
        String[] records = line.split(",[ ]");
        String employeeID = records[0];
        String fName = records[1];
        String lName = records[2];
        Double salary = Double.parseDouble(records[3]);
        Employee employee = new Employee(employeeID, fName, lName, salary);
        list.add(employee);
    }

标签: javacsvlinked-list

解决方案


您的问题似乎与此无关,LinkedList并且ArrayOutOfBoundsException表明该问题与拆分linerecords字符串数组正确相关,records[3]但不存在。所以检查它的长度,records你会发现它有什么问题。


推荐阅读