gpt4 book ai didi

java - 如何将文本文件中的内容存储到数组列表

转载 作者:行者123 更新时间:2023-12-01 07:57:35 25 4
gpt4 key购买 nike

我需要从内容以制表符分隔的文本文件中读取员工详细信息。我有两个类(class),如下所示:

package employee;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;

public class Employee {

public static void main(String[] args) throws IOException{

ArrayList<Employee_Info> ar_emp = new ArrayList<Employee_Info>();
BufferedReader br = null;
Employee_Info e = null;
br = new BufferedReader(new FileReader("C:/Users/home/Desktop/Emp_Details.txt"));
String line;
try {
while ((line = br.readLine()) != null) {
String data[] = line.split("\t");
e = new Employee_Info();
e.setDept_id(Integer.parseInt(data[0]));
e.setEmp_name(data[1]);
e.setCity(data[2]);
e.setSalary(Integer.parseInt(data[3]));

ar_emp.add(e);
}
for(Employee_Info i : ar_emp){
System.out.println(i.getDept_id()+","+i.getEmp_name()+","+i.getCity()+","+i.getSalary());

}
br.close();

} catch (IOException io) {
io.printStackTrace();
}
}
}

package employee;

public class Employee_Info {

private static int dept_id;
private static String emp_name;
private static String city;
private static int salary;

public static int getDept_id() {
return dept_id;
}
public static void setDept_id(int dept_id) {
Employee_Info.dept_id = dept_id;
}
public static String getEmp_name() {
return emp_name;
}
public static void setEmp_name(String emp_name) {
Employee_Info.emp_name = emp_name;
}
public static String getCity() {
return city;
}
public static void setCity(String city) {
Employee_Info.city = city;
}
public static int getSalary() {
return salary;
}
public static void setSalary(int salary) {
Employee_Info.salary = salary;
}


}

我试图读取的文本文件如下:

10  A   Denver  100000
10 B Houston 110000
10 C New York 90000
10 D Houston 95000
20 F Houston 120000
20 G New York 90000
20 H New York 90000
20 I Houston 125000
30 J Houston 92000
30 K Denver 102000
30 L Denver 102000
30 M Houston 85000

当我执行 Employee 类来打印 ArrayList ar_emp 的内容时,我得到以下重复输出:

30,M,Houston,85000
30,M,Houston,85000
30,M,Houston,85000
30,M,Houston,85000
30,M,Houston,85000
30,M,Houston,85000
30,M,Houston,85000
30,M,Houston,85000
30,M,Houston,85000
30,M,Houston,85000
30,M,Houston,85000
30,M,Houston,85000

请帮忙。

最佳答案

您将 Employee_Info 的所有属性声明为 static 字段。它们不绑定(bind)到类的实例,而是绑定(bind)到类本身。因此,该类的所有实例共享相同的值。从字段和方法中删除 static 关键字。

您应该使用 IDE(例如 Eclipse),它应该警告您有关实例上的静态方法调用的信息。

关于java - 如何将文本文件中的内容存储到数组列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28128549/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com