Java地址簿 如何防止代码中重复的联系人?
这是用于保留重复ID的代码。
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);
}
如果您想更改此代码以保留重复的名称,请执行以下操作
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);
}
解决方法
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<Person> ArrayOfContacts= new ArrayList<Person> ;
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;
}
}
我正在尝试创建一个通讯录,其中每个联系人都有一个名字,姓氏和唯一的ID。
我的问题是如何防止用户输入具有相同名字和姓氏的重复联系人?我应该在addContact方法中还是在main中实现某种检查?怎么样?
你可能想看: