【发布时间】: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; ...