Build a simple PhoneBook program.

PhoneBook.java 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import java.util.*;
  2. /**
  3. * Created by leon on 1/23/18.
  4. */
  5. public class PhoneBook {
  6. Map<String, ArrayList<String> > entries = new HashMap<String, ArrayList<String>>();
  7. public void addEntry(String name, String phoneNumber){
  8. ArrayList<String> pn = new ArrayList<String>();
  9. pn.add(phoneNumber);
  10. this.entries.put(name, pn);
  11. }
  12. public void addNumberTo(String name, String phoneNumber){
  13. for(Map.Entry<String, ArrayList<String>> entry: this.entries.entrySet()){
  14. if(name.equals(entry.getKey())){
  15. entry.getValue().add(phoneNumber);
  16. break;
  17. }
  18. }
  19. }
  20. public void removePhoneNumber(String name, String phoneNumber){
  21. for(Map.Entry<String, ArrayList<String>> entry: this.entries.entrySet()){
  22. if(name.equals(entry.getKey())){
  23. int indexOf = entry.getValue().indexOf(phoneNumber);
  24. if(indexOf >= 0){
  25. entry.getValue().remove(indexOf);
  26. break;
  27. }
  28. }
  29. }
  30. }
  31. public void removeRecord(String name){
  32. this.entries.remove(name);
  33. }
  34. public String lookUp(String name){
  35. StringBuilder sb = new StringBuilder();
  36. for(Map.Entry<String, ArrayList<String>> entry: this.entries.entrySet()){
  37. if(entry.getKey().equals(name)){
  38. for(String pn : entry.getValue()){
  39. sb.append(pn);
  40. }
  41. }
  42. }
  43. return sb.toString();
  44. }
  45. public String reverseLoopup(String phoneNumber){
  46. String name = null;
  47. for(Map.Entry<String, ArrayList<String>> entry: this.entries.entrySet()){
  48. for(String pn : entry.getValue()){
  49. if(pn.equals(phoneNumber)){
  50. name = entry.getKey();
  51. }
  52. }
  53. }
  54. return name;
  55. }
  56. public String display() {
  57. StringBuilder sb = new StringBuilder();
  58. for(Map.Entry<String, ArrayList<String>> entry :this.entries.entrySet()){
  59. sb.append(entry.getKey());
  60. sb.append(": ");
  61. for(String pn : entry.getValue()){
  62. sb.append(pn);
  63. //sb.append(" ");
  64. }
  65. }
  66. return sb.toString();
  67. }
  68. }