java - Please Help Fix My add Method -
it supposed keep contact_list in alphabetical order last name. have been @ hours , cannot figure out. added post both add method , findcontactindex method supposed find index of contact. keep getting nullpointer exceptions , other errors. need find out goes alphabetically , insert new contact there , move ones come after down, in correct order.
public void add(contact frnd) { if(numcontacts == 0) { contact_list[0] = frnd; } else { for(int = 0; < numcontacts; i++) { int x =contact_list[i].getlastname().comparetoignorecase(frnd.getlastname()); if(x < 0) { contact_list[findcontactindex(contact_list[i].getlastname())] = frnd; break; } } } numcontacts++; } /** * searches contact_list find contact last name * @param lstnm last name of contact found * @return indexofcontact index of contact has been found */ public int findcontactindex(string lstnm) { int indexofcontact = -1; // defaults @ 0 incase name not found for(int = 0; < numcontacts; i++) // once every contact { int = lstnm.compareto(contact_list[i].getlastname()); if( == 0) // if contact found { indexofcontact = i; // assign index of contact } } return indexofcontact; }
here code use array. below main method tests code.
public class contactlist { static class contact { string lastname; contact(final string lastname) { this.lastname = lastname; } @override public string tostring() { return string.format("contact[%s]", this.lastname); } } static final int max_contacts = 10; contact[] contactlist = new contact[max_contacts]; void add(final contact newcontact) { if (newcontact == null || newcontact.lastname == null) { return; } contact contacttoadd = newcontact; (int pos = 0; pos < max_contacts; pos++) { final contact current = this.contactlist[pos]; if (current == null) { // found end, we're done this.contactlist[pos] = contacttoadd; break; } else if (current.lastname.compareto(contacttoadd.lastname) > 0) { // current comes after contacttoadd this.contactlist[pos] = contacttoadd; contacttoadd = current; } } } static final string[] lastnames = { "a", "c", "e", "b", "d", null }; public static void main(final string[] args) { final contactlist contactlist = new contactlist(); (final string lastname : lastnames) { final contact contact = new contact(lastname); contactlist.add(contact); system.out.println(arrays.tostring(contactlist.contactlist)); } }
}
Comments
Post a Comment