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)建一個(gè)通訊錄,其中每個(gè)聯(lián)系人都有一個(gè)名字,姓氏和唯一的ID。
我的問題是如何防止用戶輸入具有相同名字和姓氏的重復(fù)聯(lián)系人?我應(yīng)該在addContact方法中還是在main中實(shí)現(xiàn)某種檢查?怎么樣?
相關(guān)文章:
1. mac連接阿里云docker集群,已經(jīng)卡了2天了,求問?2. ddos - apache日志很多其它網(wǎng)址,什么情況?3. 上傳圖片老是失敗是什么原因?SAE_TMP_PATH.后面跟的路徑在哪看4. javascript - 關(guān)于jquery的ajax post數(shù)據(jù)的問題5. 前端 - 我有一個(gè)建站程序,但是多個(gè)文件夾下的HTML模板代碼沒有進(jìn)行縮進(jìn)格式化,請問用什么軟件可以批量格式化一下代碼?6. android-studio - Win10下修改Windows用戶文件夾名user,導(dǎo)致Android Studio報(bào)錯(cuò)無法使用7. phpstudy pro小皮面板經(jīng)常報(bào)這個(gè)nginx: [emerg] CreateFile【急】8. thinkphp5.1學(xué)習(xí)時(shí)遇到session問題9. angular.js - angular 路由為什么一直請求css和js文件10. javascript - setTimeout的延遲時(shí)間,是從什么時(shí)間段開始算起的?
