I have a text file of employee entries as follows:
000, first name1, middle name1
001, first name2, middle name2
002, first name3, middle name3
003, first name4, middle name4
004, first name5, middle name5
And I have a class Employee as follows:
public class Employee {
public int id;
public String fName;
public String mName;
public String lName;
}
I've read the contents of the file into an array. But what I want is to construct an array of objects of class Employee, and a way for each attribute of the class to be initialised with each entry. Something like this:
Employee e[] = new Employee[5];
Checking the details of each object in the array...
e[0].id = 000
e[0].fName = "first name1"
e[0].mName = "middle name1"
e[0].lName = "last name1"
Then,
e[1].id = 001
And so on...
Is there any way I can do this?
Read the file and loop over its content line by line. Then parse the lines and create a
new Employee()
in each iteration. Set your values, such as id and name. Finally, add your newEmployee
instance to aList<Employee>
and continue with the next entry.Also, there are CSV libraries that can handle all the nasty parts of reading a file that has comma separated values. I'd suggest using OpenCSV, for example.
Since you already read the file into array (of string I suppose).
There you go... you have an array of employees.
try :
Employee.java
Here already answers posted but I still gonna post mine...
}