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) ?
  31. phoneBook.get(name)
  32. .toString()
  33. .replaceAll("[\\[\\]]", "")
  34. : "N/A";
  35. }
  36. public String reverseLookup(String phoneNumber) {
  37. String output = "";
  38. Set<String> keys = phoneBook.keySet();
  39. for (String key : keys) {
  40. if (phoneBook.get(key).contains(phoneNumber)) {
  41. output = key;
  42. }
  43. }
  44. return output.equals("") ? "N/A" : output;
  45. }
  46. public String display() {
  47. return phoneBook.toString().replaceAll("[{}=,]", "")
  48. .replaceAll("\\[", " - ")
  49. .replaceAll("\\]", "\n");
  50. }
  51. public TreeMap getPhoneBook() {
  52. return phoneBook;
  53. }
  54. }