Build a simple PhoneBook program.

PhoneBook.java 1.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /**
  2. * Created by leon on 1/23/18.
  3. */
  4. import java.util. *;
  5. public class PhoneBook {
  6. TreeMap<String, String> phoneBook = new TreeMap<String, String>();
  7. public String add(String name, String number) {
  8. phoneBook.put(name, number);
  9. return name + " " + number;
  10. }
  11. public String remove(String name) {
  12. phoneBook.remove(name);
  13. return name;
  14. }
  15. public String lookup(String name) {
  16. return phoneBook.get(name);
  17. }
  18. public String reverseLookup(String number) {
  19. for(Map.Entry<String, String> entry : phoneBook.entrySet()) {
  20. String value = entry.getValue();
  21. if(value.equals(number)) {
  22. return entry.getKey();
  23. }
  24. }
  25. return "";
  26. }
  27. public void display() {
  28. for(Map.Entry<String, String> entry : phoneBook.entrySet()) {
  29. String value = entry.getValue();
  30. System.out.println(entry.getKey() + " -> " + entry.getValue());
  31. }
  32. }
  33. }