Question

Requirements Create an Address Book class in Java for general use with the following behaviors: 1. Constructor: public Addres
2. Method: public void addContact (Contact newContact) Add a new contact into the address book: . Neither the first name nor
3. Method: public void deleteContact (String firstName, String lastName) Delete from the address book a contact whose first n

4. Method: public Contact[] searchByLastName (String lastName) Search all contacts by the last name and return matching conta
Apparently, you need to define a record class called Contact with the following String fields: firstName, lastName, email and
Specify and implement the following operation for the Address Book class: public Contact[] searchByLastName Partial (String p
0 0
Add a comment Improve this question Transcribed image text
Answer #1

EmptyNameException.java

public class EmptyNameException extends Exception{
  
public EmptyNameException(String msg)
{
super(msg);
}
}

ContactNotFoundException.java

public class ContactNotFoundException extends Exception{
  
public ContactNotFoundException(String msg)
{
super(msg);
}
}

DuplicateContactException.java

public class DuplicateContactException extends Exception{
  
public DuplicateContactException(String msg)
{
super(msg);
}
}

Contact.java

public class Contact {
  
private String firstName, lastName, email, phone;
  
public Contact()
{
this.firstName = this.lastName = this.email = this.phone = "";
}
  
public Contact(String firstName, String lastName) throws EmptyNameException
{
if(firstName.equals("") || firstName.trim().equals("") || lastName.equals("") || lastName.trim().equals(""))
throw new EmptyNameException("First/Last name cannot be empty!");
  
this.firstName = firstName;
this.lastName = lastName;
this.email = this.phone = "";
}

public Contact(String firstName, String lastName, String email, String phone) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.phone = phone;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getPhone() {
return phone;
}

public void setPhone(String phone) {
this.phone = phone;
}
  
@Override
public String toString()
{
return("Name: " + this.firstName + " " + this.lastName + ", Email: " + this.email + ", Phone: " + this.phone);
}
  
public boolean equals(Contact other)
{
return (this.firstName.equalsIgnoreCase(other.getFirstName()) &&
this.lastName.equalsIgnoreCase(other.getLastName()));
}
}

AddressBook.java

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Scanner;

public class AddressBook {
private ArrayList<Contact> contacts;
private static final String FILE = "contacts.dat";
  
public AddressBook()
{
this.contacts = new ArrayList<>();
  
// reads input file and populate all contacts to the list
Scanner fileReader;
try
{
fileReader = new Scanner(new File(FILE));
while(fileReader.hasNextLine())
{
String line = fileReader.nextLine().trim();
String[] data = line.split(",");
String firstName = data[0];
String lastName = data[1];
String email = data[2];
String phone = data[3];
  
this.contacts.add(new Contact(firstName, lastName, email, phone));
}
fileReader.close();
}catch(FileNotFoundException fnfe){
System.exit(1);
}
}
  
public void addContact(Contact newContact) throws EmptyNameException, DuplicateContactException, IOException
{
if(newContact.getFirstName().equals("") || newContact.getFirstName().trim().equals("")
|| newContact.getLastName().equals("") || newContact.getLastName().trim().equals(""))
throw new EmptyNameException("First/Last name cannot be empty!");
  
for(Contact con : this.contacts)
{
if(con.equals(newContact))
throw new DuplicateContactException(("Duplicate contact found!"));
}
  
this.contacts.add(newContact);
saveContactsToDisk();
}
  
private void saveContactsToDisk() throws IOException
{
FileWriter fw;
PrintWriter pw;
  
fw = new FileWriter(new File(FILE));
pw = new PrintWriter(fw);
  
for(Contact con : this.contacts)
{
pw.write(con.getFirstName() + "," + con.getLastName() + "," + con.getEmail() + "," + con.getPhone()
+ System.lineSeparator());
}
  
pw.flush();
fw.close();
pw.close();
}
  
public void deleteContact(String firstName, String lastName) throws EmptyNameException, ContactNotFoundException, IOException
{
if(firstName.equals("") || firstName.trim().equals("") || lastName.equals("") || lastName.trim().equals(""))
throw new EmptyNameException(("First/Last name cannot be empty!"));
  
int index = -1;
boolean found = false;
for(int i = 0; i < this.contacts.size(); i++)
{
if(this.contacts.get(i).getFirstName().equalsIgnoreCase(firstName) &&
this.contacts.get(i).getLastName().equalsIgnoreCase(lastName))
{
found = true;
index = i;
break;
}
}
  
if(!found)
throw new ContactNotFoundException("No contact with name " + firstName + " " + lastName + " were found!");
  
// contact found at index
this.contacts.remove(index);
saveContactsToDisk();
}
  
public Contact[] searchByLastName(String lastName) throws EmptyNameException
{
if(lastName.equals("") || lastName.trim().equals(""))
throw new EmptyNameException(("First/Last name cannot be empty!"));
  
ArrayList<Contact> searchedContacts = new ArrayList<>();
  
for(int i = 0; i < this.contacts.size(); i++)
{
if(this.contacts.get(i).getLastName().equalsIgnoreCase(lastName))
searchedContacts.add(this.contacts.get(i));
}
  
return (Contact[]) searchedContacts.toArray(new Contact[0]);
}
  
public Contact[] list()
{
return (Contact[]) this.contacts.toArray(new Contact[0]);
}
  
public Contact[] searchByLastNamePartial(String partialLastName) throws EmptyNameException
{
if(partialLastName.equals("") || partialLastName.trim().equals(""))
throw new EmptyNameException(("First/Last name cannot be empty!"));
  
ArrayList<Contact> searchedContacts = new ArrayList<>();
  
for(int i = 0; i < this.contacts.size(); i++)
{
if(this.contacts.get(i).getLastName().contains(partialLastName))
searchedContacts.add(this.contacts.get(i));
}
  
return (Contact[]) searchedContacts.toArray(new Contact[0]);
}
}

AddressBookTester.java (Main class)

import java.io.IOException;

public class AddressBookTester {
  
public static void main(String[] args)
{
System.out.println("Attempting to read disk for contacts..");
AddressBook addressBook = new AddressBook();
  
System.out.println("\nDisplaying all contacts read from disk..");
for(int i = 0; i < addressBook.list().length; i++)
{
System.out.println(addressBook.list()[i]);
}
  
System.out.println("\nAttempting to add an empty Contact..");
try {
addressBook.addContact(new Contact(" ", " ", "[email protected]", "445698712"));
} catch (EmptyNameException | DuplicateContactException | IOException ex) {
System.out.println(ex.getMessage());
}
  
System.out.println("\nAttempting to add a duplicate Contact..");
try {
addressBook.addContact(new Contact("Alice", "Stuart", "[email protected]", "445698712"));
} catch (EmptyNameException | DuplicateContactException | IOException ex) {
System.out.println(ex.getMessage());
}
  
System.out.println("\nAttempting to add a new Contact..");
try {
addressBook.addContact(new Contact("Alakha", "Measil", "[email protected]", "1169987231"));
} catch (EmptyNameException | DuplicateContactException | IOException ex) {
System.out.println(ex.getMessage());
}
System.out.println("Displaying all contacts read from disk..");
for(int i = 0; i < addressBook.list().length; i++)
{
System.out.println(addressBook.list()[i]);
}
  
System.out.println("\nAttempting to delete a contact not present..");
try {
addressBook.deleteContact("Wannah", "Halfboy");
} catch (EmptyNameException | ContactNotFoundException | IOException ex) {
System.out.println(ex.getMessage());
}
  
System.out.println("\nAttempting to delete a contact present (Alice Stuart)..");
try {
addressBook.deleteContact("Alice", "Stuart");
} catch (EmptyNameException | ContactNotFoundException | IOException ex) {
System.out.println(ex.getMessage());
}
System.out.println("Displaying all contacts read from disk..");
for(int i = 0; i < addressBook.list().length; i++)
{
System.out.println(addressBook.list()[i]);
}
  
System.out.println("\nAttempting to search contacts by last name (Weasely)..");
try {
for(int i = 0; i < addressBook.searchByLastName("Weasely").length; i++)
{
System.out.println(addressBook.searchByLastNamePartial("Weasely")[i]);
}
} catch (EmptyNameException ex) {
System.out.println(ex.getMessage());
}
  
System.out.println("\nAttempting to search contacts by partial last name (son)..");
try {
for(int i = 0; i < addressBook.searchByLastNamePartial("son").length; i++)
{
System.out.println(addressBook.searchByLastNamePartial("son")[i]);
}
} catch (EmptyNameException ex) {
System.out.println(ex.getMessage());
}
}
}

******************************************************************** SCREENSHOT *******************************************************

run: Attempting to read disk for contacts.. Displaying all contacts read from disk.. Name: Henry Johnson, Email: hj@hotmail.c

STOCROTESTETICA moy m oyonova CroTTEOTECTIEDOT Attempting to add an empty Contact.. First/Last name cannot be empty! Attempti

CONTACTS FILE (contacts.dat)

Contact.javax AddressBook.java * AddressBookTester.java x contacts.dat x Source History ... Q EDTB D O O Henry, Johnson, hi@h

Add a comment
Know the answer?
Add Answer to:
Requirements Create an Address Book class in Java for general use with the following behaviors: 1....
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Create a class named Module2. You should submit your source code file (Module2.java). The Module2 class...

    Create a class named Module2. You should submit your source code file (Module2.java). The Module2 class should contain the following data fields and methods (note that all data and methods are for objects unless specified as being for the entire class) Data fields: A String object named firstName A String object named middleName A String object name lastName Methods: A Module2 constructor method that accepts no parameters and initializes the data fields from 1) to empty Strings (e.g., firstName =...

  • Fix the following null pointer error. import java.util.*; import java.io.*; public class PhoneBook { public static...

    Fix the following null pointer error. import java.util.*; import java.io.*; public class PhoneBook { public static void main(String[]args)throws IOException { PhoneBook obj = new PhoneBook(); PhoneContact[]phBook = new PhoneContact[20]; Scanner in = new Scanner(System.in); obj.acceptPhoneContact(phBook,in); PrintWriter pw = new PrintWriter("out.txt"); obj.displayPhoneContacts(phBook,pw); pw.close(); } public void acceptPhoneContact(PhoneContact[]phBook, Scanner k) { //void function that takes in the parameters //phBook array and the scanner so the user can input the information //declaring these variables String fname = ""; String lname = ""; String...

  • DESCRIPTION Create a C++ program to manage phone contacts. The program will allow the user to...

    DESCRIPTION Create a C++ program to manage phone contacts. The program will allow the user to add new phone contacts, display a list of all contacts, search for a specific contact by name, delete a specific contact. The program should provide the user with a console or command line choice menu about possible actions that they can perform. The choices should be the following: 1. Display list of all contacts. 2. Add a new contact. 3. Search for a contact...

  • read the code and comments, and fix the program by INSERTING the missing code in Java...

    read the code and comments, and fix the program by INSERTING the missing code in Java THank you please import java.util.Scanner; public class ExtractNames { // Extract (and print to standard output) the first and last names in "Last, First" (read from standard input). public static void main(String[] args) { // Set up a Scanner object for reading input from the user (keyboard). Scanner scan = new Scanner (System.in); // Read a full name from the user as "Last, First"....

  • Write a class called Course_xxx that represents a course taken at a school. Represent each student...

    Write a class called Course_xxx that represents a course taken at a school. Represent each student using the Student class from the Chapter 7 source files, Student.java. Use an ArrayList in the Course to store the students taking that course. The constructor of the Course class should accept only the name of the course. Provide a method called addStudent that accepts one Student parameter. Provide a method called roll that prints all students in the course. Create a driver class...

  • Write in C++ please: Write a class named MyVector using the following UML diagram and class...

    Write in C++ please: Write a class named MyVector using the following UML diagram and class attribute descriptions. MyVector will use a linked listed instead of an array. Each Contact is a struct that will store a name and a phone number. Demonstrate your class in a program for storing Contacts. The program should present the user with a menu for adding, removing, and retrieving Contact info. MyVector Contact name: string phone: string next: Contact -head: Contact -tail: Contact -list_size:...

  • Requirements:  Your Java class names must follow the names specified above. Note that they are...

    Requirements:  Your Java class names must follow the names specified above. Note that they are case sensitive. See our template below.  BankAccount: an abstract class.  SavingAccount: a concrete class that extends BankAccount. o The constructor takes client's firstname, lastname and social security number. o The constructor should generate a random 6-digit number as the user account number. o The initial balance is 0 and the annual interest rate is fixed at 1.0% (0.01).o The withdraw method signature...

  • In Java You are going to create a PhoneRecord class containing the following properties: firstName -...

    In Java You are going to create a PhoneRecord class containing the following properties: firstName - which is a String lastName - which is a String number - which should also be a String the properties will be public, and it should have two constructors: one which simply constructs the string and another that accepts values for first name, lastname and phone number. You should also create a class called Phone Book. It should contain an array of Phone Records...

  • JAVA /** * This class stores information about an instructor. */ public class Instructor { private...

    JAVA /** * This class stores information about an instructor. */ public class Instructor { private String lastName, // Last name firstName, // First name officeNumber; // Office number /** * This constructor accepts arguments for the * last name, first name, and office number. */ public Instructor(String lname, String fname, String office) { lastName = lname; firstName = fname; officeNumber = office; } /** * The set method sets each field. */ public void set(String lname, String fname, String...

  • C++ In this assignment, you will write a class that implements a contact book entry. For...

    C++ In this assignment, you will write a class that implements a contact book entry. For example, my iPhone (and pretty much any smartphone) has a contacts list app that allows you to store information about your friends, colleagues, and businesses. In later assignments, you will have to implement this type of app (as a command line program, of course.) For now, you will just have to implement the building blocks for this app, namely, the Contact class. Your Contact...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT