Build a simple PhoneBook program.

PhoneBook.java 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. //JN 2018
  2. import java.util.*;
  3. public class PhoneBook {
  4. private TreeMap<String, ArrayList<String>> phoneBook;
  5. public PhoneBook() {
  6. phoneBook = new TreeMap<String, ArrayList<String>>();
  7. }
  8. public void add(String name, String phoneNumber) {
  9. ArrayList<String> input = phoneBook.containsKey(name) ?
  10. phoneBook.get(name)
  11. : new ArrayList<String>();
  12. input.add(phoneNumber);
  13. phoneBook.put(name, input);
  14. }
  15. public void remove (String phoneNumber) {
  16. ArrayList<String> edit = new ArrayList<String>();
  17. Set<String> keys = phoneBook.keySet();
  18. for (String key : keys) {
  19. if (phoneBook.get(key).contains(phoneNumber)) {
  20. edit = phoneBook.get(key);
  21. edit.remove(edit.indexOf(phoneNumber));
  22. phoneBook.put(key, edit);
  23. }
  24. }
  25. }
  26. public void removeEntry(String name) {
  27. phoneBook.remove(name);
  28. }
  29. public String lookup(String name) {
  30. return phoneBook.containsKey(name) ? format(phoneBook.get(name)): "N/A";
  31. }
  32. public String format(ArrayList<String> numbers) {
  33. return numbers.toString().replaceAll("[\\[\\]]", "");
  34. }
  35. public String reverseLookup(String phoneNumber) {
  36. String output = "";
  37. Set<String> keys = phoneBook.keySet();
  38. for (String key : keys) {
  39. if (phoneBook.get(key).contains(phoneNumber)) {
  40. output = key;
  41. }
  42. }
  43. return output.equals("") ? "N/A" : output;
  44. }
  45. public String display() {
  46. return phoneBook.toString().replaceAll("[{}=,]", "")
  47. .replaceAll("\\[", " - ")
  48. .replaceAll("\\]", "\n");
  49. }
  50. public TreeMap getPhoneBook() {
  51. return phoneBook;
  52. }
  53. }