Write a class named Customer as: Customer - lastName: String - firstName: String
ID: 3626388 • Letter: W
Question
Write a class named Customer as:
Customer
- lastName: String
- firstName: String
+ getLastName(): String
+ setLastName(String lastName): void
+ getFirstName(): String
+ setFirstName(String firstName): void
Using Customer class write a program that reads all customers’ name in a customers.txt file then displays all customers’ name in ascending order of lastName ( if equals lastName then sort by firstName).
Hint:
- class CustomerName implements Comparable
- Using support class Collections to sort all customers’ name.
- Using RandomAccessFile class to read customers.txt file.
- Using String.split() method to split a line into fields.
Explanation / Answer
import java.util.*;
class Customer implements Comparable {
private String lastname;
private String firstname;
public String getLastName()
{
return lastname;
}
public String getFirstName()
{
return firstname;
}
public void setLastName(String lname)
{
lastname=lname;
}
public void setFirstName(String fname)
{
firstname=fname;
}
public int compareTo(Object obj) {
if (obj instanceof Customer) {
Customer cust = (Customer) obj;
if (this.lastname.compareTo(cust.getLastName())>0)
return 1;
else if (this.lastname.compareTo(cust.getLastName())==0)
{
if (this.firstname.compareTo (cust.getFirstName())>0)
{
return 1;
}
}
else
return -1;
}
return 0;
}
public static void main(String[] args) {
List<Customer> list = new ArrayList<Customer>();
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter File name : ");
String str = in.readLine();
File file = new File(str);
if(!file.exists())
{
System.out.println("File does not exist.");
System.exit(0);
}
try{
//Open the file for both reading and writing
RandomAccessFile rand = new RandomAccessFile(file,"r");
rand.seek(0);
String name = rand.readLine();
while(name != null)
{
Customer c= new Customer();
String[] temp;
temp= name.split(" ");
c1.setFirstname(temp[1]);
c1.setLastname(temp[0]);
String name = rand.readLine();
list.add(c);
}
Collection.sort(list);
for(int i=0;i<list.size();i++)
{
System.out.println(list.get(i).getLastName()+" "+list.get(i).getFirstName());
}
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.