我需要从文本文件中读取员工详细信息,该文件的内容以制表符分隔。我有两个课程,如下所示:
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
请帮忙。
答案 0 :(得分:3)
从Employee_Info类的所有字段和方法中删除静态,因为static只表示一个值,而且在类级别也是如此(无论您创建任何数量的对象)。
答案 1 :(得分:3)
您已将Employee_Info
的所有属性声明为static
字段。这些不是绑定到类的实例,而是绑定到类本身。因此,该类的所有实例共享相同的值。从字段和方法中删除static
关键字。
您应该使用IDE(例如Eclipse),它应该警告您实例上的静态方法调用。