Create a Person class containing the following state and behavior as identified
ID: 3828541 • Letter: C
Question
Create a Person class containing the following state and behavior as identified below. In addition, you must also create a PersonTest class to store at least five Person using an arraylist. Create a text file that that is to be created by the program which contains the Person objects where each object is represented on a separate line with each attribute separated by a comma and name this text file PersonsInfo.txt.
Create a method that reads from the file, creates one Person object per line, and stores the object in an ArrayList object. Write the stored sorted objects by last name and display last name and first name to the console. For example, Salisbury, Robert.
First Name
Last Name
Age
Gender
SSN
First Name
Last Name
Age
Gender
SSN
Explanation / Answer
JAVA PROGRAM :
import java.util.*;
import java.io.*;
class Person{
private String firstName, lastName, gender, SSN;
private int age;
public Person(String firstName, String lastName, String gender, String SSN, int age) {
this.firstName = firstName;
this.lastName = lastName;
this.gender = gender;
this.SSN = SSN;
this.age = age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getSSN() {
return SSN;
}
public void setSSN(String SSN) {
this.SSN = SSN;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
public class Sample1 {
public static void main(String args[]) throws IOException {
String fileName = "P://PersonsInfo.txt";
Scanner obj = new Scanner(new File(fileName));
ArrayList<Person> al = new ArrayList();
while(obj.hasNext()){
String details[] = obj.nextLine().trim().split(",");
Person p = new Person(details[0].trim(),details[1].trim(),details[2].trim(),details[3].trim(),Integer.parseInt(details[4].trim()));
al.add(p);
}
Collections.sort(al,new Comparator<Person>(){
@Override
public int compare(Person o1, Person o2) {
return o1.getLastName().compareTo(o2.getLastName());
}
});
for(Person x : al){
System.out.println(x.getLastName()+" "+x.getFirstName());
}
}
}
PersonsInfo.txt file ;
Prudhvi,Maddala,Male,900619,22
Sravan,pandranki,Male,1232,23
Gayatri,amara,Female,908813,22
OUTPUT:
Maddala Prudhvi
amara Gayatri
pandranki Sravan