adding and checking an Entry in Java in an Address Book
I have an Address Book program it can:
- Add an Entry
- Delete an Entry
- Update an Entry
- View all Entries
- 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
- Check for NULL input
- Check for blank input
- Check for absurd name (like numeric names, if not allowed)
- 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.
- override equals(...) and hashCode() in AddressBookEntry based on the name property
- use HashSet to store AddressBookEntry instead of an array
- use contains(...) method to see if this object already exisits. HashSet has a big O of O(1) for contains
精彩评论