Reputation: 95
I need to read the employee details from a text file whose content is tab separated. I have two classes as shown below :
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();
}
}
}
and
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;
}
}
The text file I am trying to read is as below :
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
When I execute the Employee class to print the content of ArrayList ar_emp, I get the below repeated output :
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
Please help.
Upvotes: 0
Views: 1688
Reputation: 7771
You declared all properties of Employee_Info
as static
fields. These are not bound to an instance of the class but rather to the class itself. Therefore, all instances of the class share the same values. Remove the static
keyword from both the fields and the methods.
You should use an IDE (e.g. Eclipse), it should have warned you about static method calls on instances.
Upvotes: 3