Can someone please help me with this program? 1. Add code to the Customer class
ID: 650359 • Letter: C
Question
Can someone please help me with this program?
1. Add code to the Customer class to implement the Comparable interface. The compareTo method you create should compare the email field of the current customer with the email field of another customer, To do that, you can't use the > and < operators because the email field is a string. Instead, you"ll need to use the compareToIgnoreCase method of the String class. This method compares the string it's executed on with the string that's passed to it as an argument. If the first string is less than the second string, this method returns a negative integer. If the first string is greater than the second string, it returns a positive integer. And if the two strings are equal, it returns 0.
2. Add code to the SortedCustomerApp class that creates an array of Customer objects that can hold 3 elements, and create and assign Customer objects to those elements. Be sure that the email values you assign to the objects aren't in alphabetical order. Sort the array.
3. Code a foreach loop that prints the email, firstName, and lastName fields of each Customer object on a seperate line.
4. Test the program until you're sure it works.
Here is my source code:
Customer Class:
public class Customer
{
private String email;
private String firstName;
private String lastName;
public Customer(String email, String firstName, String lastName)
{
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
}
public void setEmail(String email)
{
this.email = email;
}
public String getEmail()
{
return email;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getFirstName()
{
return firstName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getLastName()
{
return lastName;
}
}
SortedCustomerApp class:
import java.util.Arrays;
public class SortedCustomersApp
{
public static void main(String[] args)
{
}
}
Thank you.
Explanation / Answer
// Defining CompareTo method
Public void compareTo(String email)
{
email1 = this.email;
email2 = email;
int value = email1.compareToIgnoreCase(email2);
if (value == 0)
System.out.println("Email is same");
}
}
// Part 2
import java.util.Arrays;
public class SortedCustomersApp
{
public static void main(String[] args)
{
Customer[] cust_arr = new Customer[3];
cust_arr[0].firstName = "Anna";
cust_arr[0].lastName = "Johnson";
cust_arr[0].email = "johnson5@gmail.com";
cust_arr[1].firstName = "Anni";
cust_arr[1].lastName = "Sarandon";
cust_arr[1].email = "Asarandon@gmail.com";
cust_arr[2].firstName = "Manu";
cust_arr[2].lastName = "Singh";
cust_arr[2].email = "Msingh5@gmail.com";
Arrays.sort(cust_arr);
}
}
// Part 3
for (int i =0; i<3; i++)
{
System.out.println("First Name Last Name Email");
System.out.println(cust_arr[i].firstName + " " + cust_arr[i].lastName + " " + cust_arr[i].email);
}