Simple Phonebook

PhoneBook.java 2.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. import java.util.TreeMap;
  2. import java.util.Set;
  3. import java.util.ArrayList;
  4. /**
  5. * Created by leon on 1/23/18.
  6. * Updated by allison on 5/30/18
  7. */
  8. public class PhoneBook {
  9. TreeMap<String, ArrayList<String>> myFriendsDigits;
  10. public PhoneBook() {
  11. myFriendsDigits = new TreeMap<String, ArrayList<String>>();
  12. }
  13. public void add(String name, String phoneNumber) {
  14. if (lookup(name).equals("Not Found")){
  15. ArrayList<String> soManyDigits = new ArrayList<String>();
  16. soManyDigits.add(phoneNumber);
  17. myFriendsDigits.put(name, soManyDigits);
  18. }
  19. else {
  20. ArrayList<String> soManyDigits = myFriendsDigits.get(name);
  21. soManyDigits.add(phoneNumber);
  22. }
  23. }
  24. public void add(String name, ArrayList<String> phoneNumbers) {
  25. myFriendsDigits.put(name, phoneNumbers);
  26. }
  27. public void remove(String name) {
  28. myFriendsDigits.remove(name);
  29. }
  30. public void remove(String name, int phoneNumberIndex) {
  31. ArrayList phoneNumbers = myFriendsDigits.get(name);
  32. phoneNumbers.remove(phoneNumberIndex);
  33. }
  34. public String lookup(String name) {
  35. ArrayList<String> phoneNumbers = myFriendsDigits.get(name);
  36. if (phoneNumbers != null) {
  37. return getPhoneNumberString(phoneNumbers);
  38. }
  39. else {
  40. return "Not Found";
  41. }
  42. }
  43. public String reverseLookup(String phoneNumber) {
  44. Set<String> names = myFriendsDigits.keySet();
  45. for (String name : names) {
  46. if (searchPhoneNumberList(myFriendsDigits.get(name), phoneNumber)){
  47. return name;
  48. }
  49. }
  50. return "Not Found";
  51. }
  52. public void display() {
  53. Set<String> names = myFriendsDigits.keySet();
  54. for (String name : names){
  55. System.out.println("Name: " + name + ": " + myFriendsDigits.get(name));
  56. }
  57. }
  58. private boolean searchPhoneNumberList(ArrayList<String> phoneNumbers, String theMagicNumber) {
  59. boolean found = false;
  60. for (int i = 0; i < phoneNumbers.size(); i++) {
  61. if (phoneNumbers.get(i).equals(theMagicNumber)) {
  62. found = true;
  63. break;
  64. }
  65. }
  66. return found;
  67. }
  68. private String getPhoneNumberString(ArrayList<String> phoneNumbers) {
  69. StringBuilder formattedNumbers = new StringBuilder();
  70. for (int i = 0; i < phoneNumbers.size(); i++) {
  71. if (i == phoneNumbers.size() - 1) {
  72. formattedNumbers.append(phoneNumbers.get(i));
  73. }
  74. else {
  75. formattedNumbers.append(phoneNumbers.get(i) + ", ");
  76. }
  77. }
  78. return formattedNumbers.toString();
  79. }
  80. }