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

}

  • 2
    You should explain how "none of them worked," and "I tried the sort method but it didnt work.". What was the result? – Scratte Nov 12 '20 at 00:08

2 Answers2

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","a@b.com");
        Contact c2 = new Contact("VA" , "AA", "000-987-9876","a@b.com");
        Contact c3 = new Contact("SA" , "AA", "000-987-9876","a@b.com");
        Contact c4 = new Contact("AC" , "AB", "000-987-9876","a@b.com");

        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","a@b.com");
        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;
    }
}

Preeti
  • 222
  • 1
  • 8
  • 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 Nov 11 '20 at 23:57
  • 5
    @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 Nov 12 '20 at 00:03
  • @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 Nov 12 '20 at 00:08
  • @computercarguy I understand what you're saying, though this post is tagged "java" :) – Scratte Nov 12 '20 at 00:14
  • @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. – computercarguy Nov 12 '20 at 00:22
  • @computercarguy I see. I expect that's what 10K reputation point delete votes are used for. Removing Answers that are given in the wrong language. Note that just because you've seen something, doesn't mean it's OK. It does happen sometimes when the Question author has added the proper tag later than Answers have come in, which is a different situation. Note: This particular Question is lacking details. None of us know what they've tried and how it didn't work for them. They've not included essential code meaning it doesn't even compile. The title is unrelated to the body of their post too. – Scratte Nov 12 '20 at 00:28
  • @Scratte, IDK, I think the title matches the body well and the whole things is pretty straight forward, even if they did leave off the class definition. It's better than many other Q's I've seen that get upvotes and lots of Answers. – computercarguy Nov 12 '20 at 00:33
  • @computercarguy Yes, you're right about the title matching the body. My apologies. I suppose one could just use [ void sort​(T[\] a, Comparator super T> c)](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/Arrays.html#sort(T%5B%5D,java.util.Comparator)) of the `Arrays` class. – Scratte Nov 12 '20 at 00:41
  • Hi, I tried to replicate my own version of the codes you sent and took the suggestion of the one below this answer, I think its almost working except that the actual values are not showing. – Paulbatsantos Nathaniel Nov 12 '20 at 02:19
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.

computercarguy
  • 2,173
  • 1
  • 13
  • 27