Java地址簿。如何防止代碼中重復(fù)的聯(lián)系人?
這是用于保留重復(fù)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);}
如果您想更改此代碼以保留重復(fù)的名稱,請執(zhí)行以下操作
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; }}
我正在嘗試創(chuàng)建一個通訊錄,其中每個聯(lián)系人都有一個名字,姓氏和唯一的ID。
我的問題是如何防止用戶輸入具有相同名字和姓氏的重復(fù)聯(lián)系人?我應(yīng)該在addContact方法中還是在main中實現(xiàn)某種檢查?怎么樣?
相關(guān)文章:
1. spring-mvc - spring-session-redis HttpSessionListener失效2. html5和Flash對抗是什么情況?3. 運(yùn)行python程序時出現(xiàn)“應(yīng)用程序發(fā)生異常”的內(nèi)存錯誤?4. javascript - QQ第三方登錄的問題5. node.js - mongodb查找子對象的名稱為某個值的對象的方法6. 測試自動化html元素選擇器元素ID或DataAttribute [關(guān)閉]7. 在mac下出現(xiàn)了兩個docker環(huán)境8. 利用IPMI遠(yuǎn)程安裝centos報錯!9. javascript - 在 model里定義的 引用表模型時,model為undefined。10. 淺談Vue使用Cascader級聯(lián)選擇器數(shù)據(jù)回顯中的坑

網(wǎng)公網(wǎng)安備