Build a simple PhoneBook program.

PhoneBook.java 1.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import java.util.*;
  2. import java.util.TreeMap;
  3. import java.util.Set;
  4. import java.util.Map;
  5. import java.util.Iterator;
  6. public class PhoneBook {
  7. String phoneNumber;
  8. Map<String, String> pb = new TreeMap <String, String>();
  9. public PhoneBook(){
  10. }
  11. public void add(String name, String phoneNumber){
  12. pb.put(name, phoneNumber);
  13. }
  14. public void remove(String name){
  15. pb.remove(name);
  16. }
  17. public String display(){
  18. Set set = pb.entrySet();
  19. Iterator it = set.iterator();
  20. StringBuilder display = new StringBuilder();
  21. while(it.hasNext()) {
  22. Map.Entry me = (Map.Entry)it.next();
  23. display.append(me.getKey() + " : " + me.getValue() + "\n");
  24. }
  25. return display.toString();
  26. }
  27. public String lookup(String name){
  28. String phone = pb.get(name);
  29. return phone;
  30. }
  31. public String reverseLookup(String phoneNumber){
  32. String key= null;
  33. for(Map.Entry entry: pb.entrySet()){
  34. if(phoneNumber.equals(entry.getValue())){
  35. key = entry.getKey().toString();
  36. break;
  37. }
  38. }
  39. return key;
  40. }
  41. public int size() {
  42. return pb.size();
  43. }
  44. }