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); elseSystem.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中实现某种检查?怎么样?
相关文章:
1. docker images显示的镜像过多,狗眼被亮瞎了,怎么办?2. css - ul ol前边的标记如何调整样式呢3. golang - 用IDE看docker源码时的小问题4. docker-compose 为何找不到配置文件?5. dockerfile - 为什么docker容器启动不了?6. dockerfile - [docker build image失败- npm install]7. java - servlet的init方法和选择Filter的init方法来加载配置文件,二者有何区别?8. android - 哪位大神知道java后台的api接口的对象传到前端后输入日期报错,是什么情况?求大神指点9. css - chrome浏览器input记录上次cookie信息后,有个黄色背景~如何去除!10. javascript - 求一款靠谱点的移动端图片查看器插件,老司机速进!

网公网安备