开发者

adding and checking an Entry in Java in an Address Book

I have an Address Book program it can:

  1. Add an Entry
  2. Delete an Entry
  3. Update an Entry
  4. View all Entries
  5. View specific entry

All functions well, but my problem is I want to check on开发者_运维技巧ce the user has inputted a NAME if it already exists

This is my addEntry method:

public void addEntry() {

        entry[counter] = new AddressBookEntry();
        entry[counter].setName(getNonBlankInput("Enter Name: "));
        entry[counter].setAdd(getNonBlankInput("Enter Address: "));
        entry[counter].setPhoneNo(getNonBlankInput("Enter Phone No.: "));
        entry[counter].setEmail(getNonBlankInput("Enter E-mail Address: "));
        counter++;

}

Please help me to add some conditions that will filter the user input. Like, if the user inputted a name ALREADY EXISTS.

Thanks in advance


Use HashMap as storage with Keys as UserName. You can check if user exists by performing containsKey method of HashMap. Also, it is advisable to

  1. Check for NULL input
  2. Check for blank input
  3. Check for absurd name (like numeric names, if not allowed)
  4. Store keys in same case i.e. either in lower-case or in upper case. And while looking for duplicate make sure that your input has converted to that case.

//this is your address-book with unique User-Name
private static final HashMap<String, AddressBookEntry> addressBook = new HashMap<String, AddressBookEntry>();
...
...
boolean addEntry(){
    boolean isNewEntry = true;
    //getNonBlankInput should check for valid name
    String name = getNonBlankInput("Enter Name: ");
    if(!addressBook.containsKey(name.toLowerCase())){
        AddressBookEntry entry  = new AddressBookEntry();
        entry.setName(name);
        entry.setAdd(getNonBlankInput("Enter Address: "));
        entry.setPhoneNo(getNonBlankInput("Enter Phone No.: "));
        entry.setEmail(getNonBlankInput("Enter E-mail Address: "));
        addressBook.put(name.toLowerCase(), entry);
    }else{
        isNewEntry = false;
    }
    return isNewEntry;

}


What about using a HashMap, keyed on the name? Then you could use containsKey() to see if the name's already in the HashMap before adding the entry.


You will want to store the results of getNonBlankInput in some local variables so you can check them before directly adding them into the address book. You will need a loop of some sort to check all the entries of the address book and compare the name to see if it is already contained in the address list.


  1. override equals(...) and hashCode() in AddressBookEntry based on the name property
  2. use HashSet to store AddressBookEntry instead of an array
  3. use contains(...) method to see if this object already exisits. HashSet has a big O of O(1) for contains
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜