Build a simple PhoneBook program.

PhoneBook.java 1.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  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. SortedMap<String, String> phoneBook = new TreeMap<String, String>();
  9. public void add(String name, String phoneNumber){
  10. phoneBook.put(name, phoneNumber);
  11. }
  12. public void remove(String name){
  13. phoneBook.remove(name);
  14. }
  15. public String lookup(String name){
  16. return phoneBook.get(name);
  17. }
  18. public String reverseLookup(String phoneNumber){
  19. for(Map.Entry<String, String> e : phoneBook.entrySet()){
  20. if(e.getValue().equals(phoneNumber)){
  21. return e.getKey();
  22. }
  23. }
  24. return null;
  25. }
  26. public void display(){
  27. System.out.printf("%-20s%-12s\n", "Name", "Phone Number");
  28. for(Map.Entry<String, String> e : phoneBook.entrySet()){
  29. String printName = e.getKey();
  30. String printNumber = e.getValue();
  31. System.out.printf(" %-20s %-12s\n", printName, printNumber);
  32. }
  33. System.out.printf("-----End of the phone book-----\n");
  34. }
  35. }