-2

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; 
}

}

1
  • 2
    You should explain how "none of them worked," and "I tried the sort method but it didnt work.". What was the result? Commented Nov 12, 2020 at 0:08

2 Answers 2

2

You need to either implement Comparable or Comparator interfaces and override their respective methods.

Also, use TreeSet to maintain the address book. All newly added contacts will be automatically sorted. I have created a quick example:-

import java.lang.Comparable;
import java.util.*;

public class ContactTester{

    public static void main(String args[]){
        Contact c1 = new Contact("PA" , "GC", "000-987-9876","[email protected]");
        Contact c2 = new Contact("VA" , "AA", "000-987-9876","[email protected]");
        Contact c3 = new Contact("SA" , "AA", "000-987-9876","[email protected]");
        Contact c4 = new Contact("AC" , "AB", "000-987-9876","[email protected]");

        TreeSet<Contact> addressBook = new TreeSet();
        addressBook.add(c1);
        addressBook.add(c2);
        addressBook.add(c3);
        addressBook.add(c4);
        
        for (Contact c : addressBook)
            System.out.println(c.toString());

        Contact c5 = new Contact("TT" , "AT", "000-987-9876","[email protected]");
        addressBook.add(c5);

        for (Contact c : addressBook)
            System.out.println("after " + c.toString());
    }
}

class Contact implements Comparable<Contact>{
    private String firstname;
    private String lastname;
    private String phoneNumber;
    private String email;

    public Contact(String firstname, String lastname, String phoneNumber, String email){
        this.firstname = firstname;
        this.lastname = lastname;
        this.phoneNumber = phoneNumber;
        this.email = email;
    }

    @Override
    public int compareTo(Contact contact){
        int last = this.lastname.compareTo(contact.lastname);
        return last ==0 ? this.firstname.compareTo(contact.firstname) : last;
    }

    @Override
    public String toString(){
        return "firstname "+ this.firstname + " lastname " + this.lastname + " phoneNumber " + this.phoneNumber + " email " + this.email;
    }
}

Sign up to request clarification or add additional context in comments.

9 Comments

I'm going to say that this is far beyond what the OP really needs. They admit they are new to programming and it's an assignment for class. Likely, the instructor wouldn't like something this advanced from a noob and could get them in hot water for going too far beyond the scope of the class as well as plagiarizing their code from the internet. It's good code, but you also have to take into account what the OP actually needs and can use.
@computercarguy But that would mean that this Answer is only for that one user. It's not. It's for everyone that wants an answer to the Question. How people use it is up to them.
@Scratte, so then really, this doesn't answer the OP's question, since they likely can't use it. I understand wanting to have an Answer for "everyone", but sometimes an Answer is just for the Question. The OP asks a specific question about their code, so the Answer should be specific to their code, not to "all code everywhere". It would be like posting C# or JavaScript code to this Q, even though it's specific to Java. It answer's other people's question, but not really the OP's.
@computercarguy I understand what you're saying, though this post is tagged "java" :)
@Scratte, yes it is, and I've seen other posts where there's 5-6 different languages in various Answers, even though the Q also specifies a language. I'm simply saying that if the OP can't use an Answer for whatever reason, then it's not any good to the OP.
|
0

It's been a while since I did Java programming, but there's a lot of formatting and some syntax advice I could give, but that's not on topic at the moment. I've edited the Q to make some things a little better to read, including putting the code in a code block, if that gets approved.

So first things first:

Your array sort is in the loop, which it shouldn't be. You should only do that after you've done all your input. At least in this case. There may be times when it's appropriate to put a sort in a loop, but not this time.

Secondly:

You also need to move the println outside the loop as well, which means you'll need to create a new loop to display all the contacts. You can reuse the i variable, since it'll be out of scope of the first loop, so there's no problems with mangling other uses of that variable.

You can also take a look at the below Question if you have any questions about that.

List an Array of Strings in alphabetical order

Third:

I said I wasn't going to talk about formatting, but I'll take a brief dive into it. Your contact variable should be a different name than your contact class. Even if that means capitalizing the class name, that should be good enough for most cases, at least while you're still learning. It's not usually good for a seasoned professional, but sometimes it happens anyway. But it should be rare.

Also, you could create a new instance of a blank contact, then simply assign the values directly to that object, instead of having the extra variables. Those variables could retain data that gets leaked to other contact. The below Question shows how to add an element to an existing array. It's about ints, but it works the same for all arrays.

Adding integers to an int array

And this Question is about how to assign to a variable from an object property. It's the opposite of what you're doing, but you just need to reverse the assignment. Their example is double height1 = oldRectangle.height;, so reversing it would be oldRectangle.height = height1;.

How to assign an object property value to a variable in Java?

Since you don't include the contact class definition, I don't know the specifics, but I'll guess that you can do something like this:

Contact newContact = new Contact(); // at the beginning of the loop
...
newContact.LastName = scanner.next();
...
newContact.FirstName = scanner.next();
...
newContact.Phone = scanner.next();
...
newContact.Email= scanner.next();
...
contact.Add(newContact); // at the end of the loop

This also assumes that a new contact doesn't require those parameters and you can just create a blank contact. If it does require those params, you can still do it but instead do new Contact("", "", "", "");. It might annoy your instructor, or it might be a requirement of the assignment to use variables and the current instantiation, with my suggestions being ahead of your current learning point.

Hmm, that wasn't so brief. Sorry. I'm sure your prof/teacher/instructor will teach you more about proper formatting and other Best Practices later, so I really won't go further than I already have.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.