12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697 |
- import java.util.Iterator;
- import java.util.Map;
- import java.util.Set;
- import java.util.SortedMap;
- import java.util.TreeMap;
- import java.util.ArrayList;
-
- public class PhoneBook {
- public TreeMap<String, ArrayList<String>> bookEntries;
-
- public PhoneBook (){
- this.bookEntries = new TreeMap<String, ArrayList<String>>();
- }
-
- public void add(String name, String phoneNumber) {
- ArrayList<String> addMe = new ArrayList<String>();
- if (bookEntries.containsKey(name)) {
- addMe = bookEntries.get(name);
- }
- addMe.add(phoneNumber);
- bookEntries.put(name, addMe);
- }
-
- public void remove(String name, String phoneNumber) {
- ArrayList listOfNumbers = new ArrayList();
- if (bookEntries.containsKey(name)) {
- listOfNumbers = bookEntries.get(name);
- listOfNumbers.remove(phoneNumber);
- }
- if (listOfNumbers.size() == 0) {
- bookEntries.remove(name);
- }
- }
-
- public void removeRecord(String name) {
- if (bookEntries.containsKey(name)) {
- bookEntries.remove(name);
- }
- }
-
- public String lookup(String name) {
- String phoneNumber = "This entry doesn't exist. Please enter valid entry.";
- if (bookEntries.containsKey(name)) {
- phoneNumber = bookEntries.get(name).toString().replace("[", "").replace("]", "");
- }
- return phoneNumber;
- }
-
- public String reverseLookup(String phoneNumber) {
- String name = "This entry doesn't exist. Please enter valid entry.";
- Set<String> keys = bookEntries.keySet();
- for(String key: keys){
- if(bookEntries.get(key).contains(phoneNumber) == true) {
- name = key;
- }
- }
- return name;
- }
-
- public void display() {
- Set<String> keys = bookEntries.keySet();
- for(String key: keys){
- System.out.println(key + ": " + bookEntries.get(key).toString().replace("[", "").replace("]", ""));
- }
- }
-
- public void main(String[] args) {
- PhoneBook myBook = new PhoneBook();
- myBook.add("Tomato", "267-945-5231");
- myBook.add("Asparagus", "305-504-1159");
- myBook.add("Eggplant", "123-345-6789");
- myBook.add("Beet", "233-464-1289");
- myBook.add("Asparagus", "454-345-4566");
- myBook.add("Leeks", "194-345-3458");
- myBook.add("Leeks", "345-209-1095");
- myBook.display();
-
- System.out.println("***");
- myBook.remove("Asparagus", "305-504-1159");
- myBook.removeRecord("Beet");
- System.out.println("Phonebook after removing Asparagus' number and Beets' record");
- myBook.display();
-
- System.out.println("***");
- System.out.println("Looking for Leeks' phone number");
- System.out.println(myBook.lookup("Leeks"));
-
- System.out.println("***");
- System.out.println("Looking for the owner of number 454-345-4566");
- System.out.println(myBook.reverseLookup("454-345-4566"));
-
- System.out.println("***");
- System.out.println("Looking for Banana's phone number");
- System.out.println(myBook.lookup("Banana"));
- }
- }
|