1

so I'm working on an address book assignment and I'm stuck on getting Comparable to sort the contacts by last name. I'm trying stuff that we haven't really learned like ArrayLists of objects, comparable and Serializable and comparable is confusing me the most.

Any tips on why the contacts aren't sorting? Second question, I wanted to try and make the first character of the first and last name an uppercase but I just couldn't figure it out so I made the whole thing uppercase in the toString method, any ideas how to get only the first char upper?

public class AddressBook implements Serializable{

private ArrayList<String> newBook = new ArrayList<String>();
private String dataFile;
private ArrayList<Contact> card =new ArrayList<Contact>(50);
private Contact[] contacts;
private int size = 0;
private int capacity = 0;
private String firstName;
private String lastName;


public static void main(String[] args) {
    AddressBook AB = new AddressBook();
    AB.addressBookMenu();
}


public void addressBookMenu() {
    Scanner scan = new Scanner(System.in);
    String option = "";

    System.out.println("PLEASE SELECT ONE OF THE FOLLOWING OPTIONS: ");
    System.out.println("\t add   --> Add a new contact ");
    System.out.println("\t find  --> Find a contact ");
    System.out.println("\t edit  --> Edit an existing contact ");
    System.out.println("\t view  --> View the current address book");
    System.out.println("\t save  --> Save the current address book");
    System.out.println("\t quit  --> quit");
    System.out.println();
    option = scan.nextLine();

    while(!(option.equalsIgnoreCase("quit"))) {
        Contact con = new Contact(firstName, lastName);
        if(option.equalsIgnoreCase("add")) {
            System.out.println("Enter First Name: ");
            String tempFirst = scan.nextLine();
            System.out.println("Enter Last Name: ");
            String tempLast = scan.nextLine();

            con.setFirstName(tempFirst);
            con.setLastName(tempLast); 
            card.add(con);  
            writeContact();
        }   

        //View address book
        if(option.equalsIgnoreCase("view")) {
            System.out.println("\tADDRESS BOOK" + "\n" +
                    "=============================");

            Collections.sort(card);
            con.getFullName();
            readContact();
        }

        System.out.println();
        System.out.println("PLEASE SELECT ONE OF THE FOLLOWING OPTIONS: ");
        System.out.println("\t add   --> Add a new contact ");
        System.out.println("\t find  --> Find a contact ");
        System.out.println("\t edit  --> Edit an existing contact ");
        System.out.println("\t view  --> View the current address book");
        System.out.println("\t save  --> Save the current address book");
        System.out.println("\t quit  --> quit");
        System.out.println();
        option = scan.nextLine();
    }
}

public void writeContact() {
    try (FileOutputStream out = new FileOutputStream("addressbook.txt")) {  
        ObjectOutputStream os = new ObjectOutputStream(out);

        os.writeObject(card);
        os.close();

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public void readContact() {
    try (FileInputStream in = new FileInputStream("addressbook.txt")) {
        ObjectInputStream is = new ObjectInputStream(in);
        ArrayList<Contact> card = (ArrayList<Contact>)is.readObject();

        for(Contact temp : card) {
            System.out.println(temp);
        }

        is.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
}

Contact Class

public class Contact implements Comparable<Contact>, Serializable{

private String firstName;
private String lastName;
private String email;
private String phone;

public Contact() {
    firstName = "";
    lastName = "";
}
public Contact(String ln, String fn) {
    lastName = ln;
    firstName = fn;
}

public void setFirstName(String fn) {
    firstName = fn;
}
public void setLastName(String ln) {
    lastName = ln;
}
public void setFullName(String fn, String ln) {
    firstName = fn;
    lastName = ln;

}

public String getFirstName() {
    return firstName;
}
public String getLastName() {
    return lastName;
}
public String getFullName() {
    return lastName + firstName;
}

public String toString() {
    return 
            "FIRST NAME: " + getFirstName().substring(0).toUpperCase() + "\t" +
            "LAST NAME: " + getLastName().substring(0).toUpperCase() + "\n";            
}

@Override
public int compareTo(Contact nextContact) {
    return lastName.compareTo(nextContact.lastName);
}

}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
NoobCoderChick
  • 617
  • 3
  • 21
  • 40
  • 1
    Please only ask *one* question per post, and ideally with a *short* but complete program demonstrating the problem. I suspect the problem is that your `readContact()` ignores the content of the collection you've just sorted... – Jon Skeet Oct 18 '15 at 07:22
  • I need to be sorting it in the readContent method? – NoobCoderChick Oct 18 '15 at 07:32
  • http://stackoverflow.com/questions/1892765/capitalize-first-char-of-each-word-in-a-string-java answers your question about capitalization of first characters – Jens Schauder Oct 18 '15 at 07:34
  • Well you certainly don't want to be printing as you read, unless the contacts were sorted before they were written... You should really debug through your code to understand what's happening. – Jon Skeet Oct 18 '15 at 07:36
  • Thanks Jens I'll check that out – NoobCoderChick Oct 18 '15 at 07:40
  • So I'm using Comparable correctly it's where I'm sorting and how it's being read? – NoobCoderChick Oct 18 '15 at 07:41

2 Answers2

2

Your problem is as follows: This code snippet

Collections.sort(card);
con.getFullName();
readContact();

is actually sorting the card collection you have, and then you call readContact() method which creates a local card collection inside it, which shadows the card collection you have in your main program, and prints its contacts, as they were written to the file before. they don't get sorted.

the solution would be like this:

if(option.equalsIgnoreCase("view")) {
    System.out.println("\tADDRESS BOOK" + "\n" +
                "=============================");

    con.getFullName(); // <------ ALSO, NOT QUITE SURE WHAT THIS IS FOR
    readContact();
}

public void readContact() {
    try (FileInputStream in = new FileInputStream("addressbook.txt")) {
        ObjectInputStream is = new ObjectInputStream(in);
        ArrayList<Contact> card = (ArrayList<Contact>)is.readObject();

        Collections.sort(card); // <----------- THIS ADDED

        for(Contact temp : card) {
            System.out.println(temp);
        }

        is.close();
    } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
noodlez040
  • 236
  • 2
  • 10
  • That did it Noodlez, thank you! Been watching videos on Comparable the last 2 hours thinking I wasn't using it correctly. I'm very new to Java and especially using objects in ArrayLists, so as far as the line you pointed out...that's a very good question lol. I think it's left over code because I've been slowly piecing this thing together and I started by just making sure I could add a object to the array list and print it out, then I created readContact() and so on...I have a headache, tomorrow I'll reread your description on what went wrong and see if I can translate to english haha – NoobCoderChick Oct 18 '15 at 07:51
1

Any tips on why the contacts aren't sorting?

They are sorting. But then you don't print the sorted card. You re-read the contacts in readContact and then print them, unsorted.

Probably you meant to write it this way instead:

if(option.equalsIgnoreCase("view")) {
    System.out.println("\tADDRESS BOOK" + "\n" +
            "=============================");

    readContact();
    Collections.sort(card);
    printContacts();
}

And in readContact change this line:

    ArrayList<Contact> card = (ArrayList<Contact>)is.readObject();

To this:

    card = (ArrayList<Contact>)is.readObject();

And move the printing out from readContact to its own method:

void printContacts() {
    for(Contact temp : card) {
        System.out.println(temp);
    }
}

Second question, [...] any ideas how to get only the first char upper?

Sure, with a helper method like this:

private String toTitleCase(String name) {
    return Character.toTitleCase(name.charAt(0)) + name.substring(1).toLowerCase();
}
janos
  • 120,954
  • 29
  • 226
  • 236
  • I actually tried that Janos, I played around with it for a while. I just did what you said to and it's still printing unsorted. – NoobCoderChick Oct 18 '15 at 07:58
  • Ah of course, because the printing was right after reading. It's not good when a method has multiple responsibilities. `readContact` should only read, and printing should be in another method, dedicated to printing. See my updated answer – janos Oct 18 '15 at 08:01
  • Ah, that's a good call, because that way I can make sorting an option and sort it anywhere I want to. Thanks Janos! I already excepted the other answer though I apologize, I wish we could except more then one – NoobCoderChick Oct 18 '15 at 15:25