Build a simple PhoneBook program.

PhoneBook.java 1.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. import java.util.*;
  2. /**
  3. * Created by leon on 1/23/18.
  4. */
  5. public class PhoneBook {
  6. String name;
  7. String phoneNumber;
  8. TreeMap<String, String> phoneBook = new TreeMap<>();
  9. public PhoneBook(TreeMap<String, String> phoneBook) {
  10. this.phoneBook = phoneBook;
  11. }
  12. public PhoneBook(){}
  13. public void add(String name, String phoneNumber){
  14. phoneBook.put(name, phoneNumber);
  15. }
  16. public void remove(String name){
  17. phoneBook.remove(name);
  18. }
  19. public String lookup(String name){
  20. return phoneBook.get(name);
  21. }
  22. public String reverseLookup(String phoneNumber) {
  23. for (Map.Entry<String, String> e : phoneBook.entrySet()) {
  24. String name = e.getKey();
  25. String thisNumber = e.getValue();
  26. if (thisNumber == phoneNumber) {
  27. return name;
  28. }
  29. }
  30. return "Name not found";
  31. }
  32. public String display() {
  33. StringBuilder sb = new StringBuilder();
  34. for (Map.Entry<String, String> e : phoneBook.entrySet()){
  35. String name = e.getKey();
  36. String thisNumber = e.getValue();
  37. sb.append(name).append(" ").append(thisNumber).append("\n");
  38. }
  39. return sb.toString();
  40. }
  41. }