使用CSV文件将对象添加到arrayList,但对象的值返回null

问题描述 投票:-1回答:1

我正在尝试使用CSV文件来创建员工对象列表,但我现在每个值都为null。值为:username,firstname,lastname,email,gender,race,id和ssn。我可以在CSV文件中读取并解析它,但是当我尝试使用对象填充列表时,它会填充它们,但每个值仍然为空。主要方法:

public static void main(String[] args) {
    String csvFile = "employee_data.csv";
    BufferedReader br = null;
    String line = "";
    String cvsSplitBy = ",";
    List<Entry> People = new ArrayList<>();
    try {
        br = new BufferedReader(new FileReader(csvFile));
        while ((line = br.readLine()) != null) {
            // use comma as separator
            String[] Labels = line.split(cvsSplitBy);                 
            Entry entry = new Entry(Labels[0], Labels[1], Labels[2], Labels[3], Labels[4], Labels[5], Labels[6], Labels[7]);
            People.add(entry);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (br != null) {
            try {
                br.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    System.out.print(People);
}

入门课程:

public class Entry {
    private String Username, Firstname, Lastname, Email, Gender, Race, ID, SSN;
    public Entry(String Username, String Firstname, String Lastname, String Email, String Gender, String Race, String ID, String SSN) {
        this.Username=null;
        this.Firstname=null;
        this.Lastname=null;
        this.Email=null;
        this.Gender=null;
        this.Race=null;
        this.ID=null;
        this.SSN=null;
    }
    @Override
    public String toString() {
        return ("Username:"+this.Username);
    }
}

我不确定为什么Entry对象被正确地添加到List中,但是Labels数组中的值没有被传输,所以username,firstname等都被标记为null,我无法弄清楚为什么

java csv object arraylist
1个回答
1
投票

我认为Entry类的构造函数需要将参数分配给类中的字段。以下内容如何:

public class Entry {

    private String Username, Firstname, Lastname, Email, Gender, Race, ID, SSN;

    public Entry(String Username, String Firstname, String Lastname, String Email, String Gender, String Race, String ID, String SSN) {
        this.Username = Username;
        this.Firstname = Firstname;
        this.Lastname = Lastname;
        this.Email = Email;
        this.Gender = Gender;
        this.Race = Race;
        this.ID = ID;
        this.SSN = SSN;
    }

    @Override
    public String toString() {
        return ("Username:" + this.Username);
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.