Java地址簿。如何防止代碼中重復的聯(lián)系人?
這是用于保留重復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);}
如果您想更改此代碼以保留重復的名稱,請執(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。
我的問題是如何防止用戶輸入具有相同名字和姓氏的重復聯(lián)系人?我應該在addContact方法中還是在main中實現(xiàn)某種檢查?怎么樣?
相關(guān)文章:
1. javascript - vue 移動端的input 數(shù)字輸入優(yōu)化2. 為什么我ping不通我的docker容器呢???3. javascript - 有什么兼容性比較好的辦法來判斷瀏覽器窗口的類型?4. 關(guān)于docker下的nginx壓力測試5. HTML5禁止img預覽該怎么解決?6. 服務器端 - 采用nginx做web服務器,C++開發(fā)應用程序 出現(xiàn)拒絕連接請求?7. javascript - npm start 運行’webpack-dev-server’報錯 Cannot find module ’webpack’8. angular.js - Ionic 集成crosswalk后生成的apk在android4.4.2上安裝失?。???9. java - 靜態(tài)屬性中的賦值和靜態(tài)代碼塊中的賦值有什么區(qū)別?10. javascript - nidejs環(huán)境設置操作一直出現(xiàn)這種問題怎么解決?
