lCreate a class Contact to store the contact information. The Contact class shou
ID: 3831303 • Letter: L
Question
lCreate a class Contact to store the contact information. The Contact class should store the contact’ first and last name, phone number, and email address. Add appropriate accessor and mutator methods.
Now write a program that uses an ArrayList of parameter type Contact to store a database of contacts. Your program should present a menu that allows the user to 1) add a contact to the list, 2) remove a contact from the list, 3) save all contacts to a file, 4) load all the contacts from a file, 5) display all contacts, 6) search for a specific contact and display it. 7) Exit from the program.
Contact Menu:
1)Add
2)Remove
3)Save
4)Load
5)Show All
6)Search
7)Exit
The searches should find any contact where any instance variable contains a target search string. For example, if “abc” is the search target, then any contact where the first name, last name, phone number, or email address contains “abc” should be shown on the display.
Your program should keep running while performing these operations and only quit if the user selects Exit from the menu. In that case, you should save all the contacts from the list to the file (before you quit from the prorgram). When you restart your program you should retrieve all the contacts from the file. In case, you first time start your program (file does not exists!) you should create an empty file (contacts.txt).
Note: You can use either text file or binary file.
Explanation / Answer
Example:
class Contact {
private String name = null;
public Contact() {
}
public Contact(String name) {
setName(name);
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
The name is private so no one can access it outside the class.
The getName is the accessor to get the name
The setName is the mutator to change the value of the name.
As you can see, accessor, mutator are just fancy words. Just add in the class whatever your assignments says that a Contact should have, make them private and add get/set methods.
Then provided that you have java 1.5 and later you can create the ArrayList and put as many as you like:
ArrayList<Contact> list = new ArrayList<Contact>();
Contact cnt1 = new Contact();
cnt1.setName("my name");
Contact cnt2 = new Contact("my other name");
list.add(cnt1);
list.add(cnt2);
for (int i=0;i<list.size();i++) {
Contact cont = list.get(i);
System.out.println("Name: "+cont.getName());
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.