Build a simple PhoneBook program.

PhoneBook.java 2.0KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import java.util.HashMap;
  2. import java.util.Map;
  3. import java.util.TreeMap;
  4. public class PhoneBook {
  5. Map<String, String> phoneBook = new HashMap<String, String>();
  6. public String add(String name, String number) {
  7. phoneBook.put(name, number);
  8. return (name + " " + phoneBook.get(name));
  9. // phoneBook.put("Albert", "302-123-4567");
  10. // phoneBook.put("Bobby", "302-111-1111");
  11. // phoneBook.put("Clyde", "302-222-2222");
  12. // phoneBook.put("Drew", "302-333-3333");
  13. //
  14. // System.out.println(phoneBook.size());
  15. //
  16. // System.out.println(phoneBook.get("Clyde" + "\n"));
  17. //
  18. // for(Map.Entry<String, String> list : phoneBook.entrySet()){
  19. //
  20. // String key = list.getKey();
  21. // String value = list.getValue();
  22. // System.out.println(key + " " + value);
  23. //
  24. // }
  25. }
  26. public String remove(String name) {
  27. phoneBook.remove(name);
  28. return name;
  29. }
  30. public String lookUp(String name) {
  31. phoneBook.get(name);
  32. return phoneBook.get(name);
  33. }
  34. public String reverseLookUp(String number) {
  35. String result = "";
  36. //need to import Entry class
  37. for (Map.Entry<String, String> entry : phoneBook.entrySet()) {
  38. if (entry.getValue().equals(number)) {
  39. result = (entry.getKey());
  40. }
  41. }
  42. return result;
  43. }
  44. public String displayPhoneBook(){
  45. String result = "";
  46. //this converts a Hash Map into a sorted Tree Map
  47. TreeMap<String, String> treePhoneBook = new TreeMap<String, String>(phoneBook);
  48. for (Map.Entry<String, String> entry : treePhoneBook.entrySet()){
  49. //must append onto the string
  50. result += (entry.getKey() + " " + entry.getValue() + "\n");
  51. }
  52. return result;
  53. }
  54. }