switch(menuChoice) {
case 1:
System.out.println("Enter your contact's first name:\n");
String fname = scnr.next();
System.out.println("Enter your contact's last name:\n");
String lname = scnr.next();
Necronomicon.addContact(new Person(fname, lname));
break;
// main truncated here for readability
import java.util.ArrayList;
public class AddressBook {
ArrayList ArrayOfContacts= new ArrayList();
public void addContact(Person p) {
ArrayOfContacts.add(p);
/*
for(int i = 0; i < ArrayOfContacts.size(); i++) {
if(ArrayOfContacts.get(i).getID() != p.getID())
ArrayOfContacts.add(p);
else
System.out.println("Sorry this contact already exists.");
}
*/
}
}
public class Person {
private String fName = null;
private String lName = null;
private static int ID = 1000;
public Person(String fName, String lName) { // Constructor I'm using to try and increment the ID each time a Person object is created starting at 1001.
this.fName = fName;
this.lName = lName;
ID = ID + 1;
}
}
I am trying to create an address book whereby each contact has a first name, last name and a unique ID.
My question is how to I prevent a user from entering in duplicate contacts with the same first and last name? Should I implement some kind of check in the addContact method or right in main? How?
解决方案
Here is the code for keeping out duplicate ID's.
public void addContact(Person p) {
for(int i = 0; i < ArrayOfContacts.size(); i++) {
Person contact = ArrayOfContacts.get(i);
if(contact.getID() == p.getID()) {
System.out.println("Sorry this contact already exists.");
return; // the id exists, so we exit the method.
}
}
// Otherwise... you've checked all the elements, and have not found a duplicate
ArrayOfContacts.add(p);
}
If you would like to change this code to keep out duplicate names, then do something like this
public void addContact(Person p) {
String pName = p.getFname() + p.getLname();
for(int i = 0; i < ArrayOfContacts.size(); i++) {
Person contact = ArrayOfContacts.get(i);
String contactName = contact.getFname() + contact.getLname();
if(contactName.equals(pName)) {
System.out.println("Sorry this contact already exists.");
return; // the name exists, so we exit the method.
}
}
// Otherwise... you've checked all the elements, and have not found a duplicate
ArrayOfContacts.add(p);
}