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. android - webview 自定義加載進度條2. 為什么我ping不通我的docker容器呢???3. javascript - 微信小程序限制加載個數4. 并發模型 - python將進程池放在裝飾器里為什么不生效也沒報錯5. mysql - 怎么讓 SELECT 1+null 等于 16. python 怎樣用pickle保存類的實例?7. linux - openSUSE 上,如何使用 QQ?8. 大家好,請問在python腳本中怎么用virtualenv激活指定的環境?9. linux - 升級到Python3.6后GDB無法正常運行?10. Python中, 仿照經典代碼實現單例, 卻出現了不是單例的的狀態, 代碼哪里出錯了 ?
