I have an assignment that goes like this: Create a program that functions as an address book. It should have entries containing the following information: first and last name, phone number and email address. The entries should be sorted by last name. Every new contact will be inserted in such a way as to maintain the alphabetical order. Upon each change a display of all the entries is required.
Ive read several articles in this site but none of them worked, I tried the sort method but it didnt work.
edit: Hi! I tried your suggestions and its now printing like this, I also updated the code. [com.mycompany.test.contact@b4c966a, com.mycompany.test.contact@2f4d3709, com.mycompany.test.contact@4e50df2e]
public class NewClass {
String firstname;
int phone;
String email;
int i=0;
public static void main(String[]args){
String lastname;
String firstname;
int phone;
String email;
Scanner scanner = new Scanner(System.in);
contact[] contacts = new contact[3];
for(int i=0; i<contacts.length; i++){
System.out.println("Please enter Last name:");
lastname = scanner.next();
System.out.println("Please enter sFirst name:");
firstname = scanner.next();
System.out.println("Please enter Phone number:");
phone = scanner.nextInt();
System.out.println("Please enter Email address:");
email = scanner.next();
contacts[i] = new contact(lastname,firstname, phone, email);
}
Arrays.sort(contacts);
for (int i=0; i<contacts.length; i++) {
System.out.println(Arrays.toString(contacts));
}
}
}
public class contact implements Comparable {
private String lastname;
private String firstname;
private int phone;
private String email;
public contact(String lastname, String firstname, int phone, String email){
this.lastname=lastname;
this.firstname=firstname;
this.phone=phone;
this.email=email;
}
public String getlastname(){
return lastname;
}
public String getfirstname(){
return firstname;
}
public int phone(){
return phone;
}
public String getlastemail(){
return email;
}
@Override
public int compareTo(contact contact){
return lastname.compareTo(contact.lastname);
}
public String tostring(){
return "Lastname: "+ this.lastname + "Firstname: " + this.firstname + "Phonenumber :" + this.phone + "Email: " + this.email;
}
}