【问题标题】:Adding objects to arrayList using a CSV file, but the values of the objects are returning null使用 CSV 文件将对象添加到 arrayList,但对象的值返回 null
【发布时间】:2018-02-17 21:33:59
【问题描述】:

我正在尝试使用 CSV 文件来创建员工对象列表,但目前每个值都为 null。值是:用户名、名字、姓氏、电子邮件、性别、种族、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);
}

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=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 对象被正确添加到列表中,但是标签数组中的值没有被传输,所以用户名、名字等都被标记为空,我不知道为什么

【问题讨论】:

  • 你为什么感到惊讶?您将 null 分配给构造函数中的每个字段:this.Username=null; this.Firstname=null; ...

标签: java csv object arraylist


【解决方案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);
    }
}

【讨论】:

    猜你喜欢
    • 2019-07-15
    • 1970-01-01
    • 2018-09-14
    • 2017-12-12
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 2016-09-26
    相关资源
    最近更新 更多