java编码实现一个地址簿,Java地址簿。如何防止代码中重复的联系人?

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 ArrayOfContacts= new ArrayList();

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);

else

System.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;

}

}

I am trying to create an address book whereby each contact has a first name, last name and a unique ID.

My question is how to I prevent a user from entering in duplicate contacts with the same first and last name? Should I implement some kind of check in the addContact method or right in main? How?

解决方案

Here is the code for keeping out duplicate ID's.

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);

}

If you would like to change this code to keep out duplicate names, then do something like this

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);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值