Build a simple PhoneBook program.

PhoneBook.java 1.1KB

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