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绑定了nginx端口 外部访问不到2. Docker for Mac 创建的dnsmasq容器连不上/不工作的问题3. docker-compose 为何找不到配置文件?4. dockerfile - [docker build image失败- npm install]5. boot2docker无法启动6. docker网络端口映射,没有方便点的操作方法么?7. ruby - 关于rails中devise登录用户名的调用问题8. html5 - 如何让H5页面在手机浏览器里和微信全屏显示9. docker api 开发的端口怎么获取?10. docker不显示端口映射呢?

网公网安备