Build a simple PhoneBook program.

PhoneBook.java 1.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import java.util.Map;
  2. import java.util.*;
  3. public class PhoneBook {
  4. Map<String,List<String>> phoneBook = new TreeMap<String,List<String>>();
  5. public PhoneBook(){
  6. }
  7. public void addEntrant(String name, String...phoneNumber){
  8. String checkName = lookup(name);
  9. if(checkName == null){
  10. phoneBook.put(name, Arrays.asList(phoneNumber));
  11. } else {
  12. System.out.println("Error, user already exists");
  13. }
  14. }
  15. public void removeEntrant(String name){
  16. phoneBook.remove(name);
  17. }
  18. public String lookup(String name){
  19. if (phoneBook.get(name) == null){
  20. return null;
  21. }
  22. StringBuilder numbersList = new StringBuilder();
  23. int counter = 0;
  24. for(String number: phoneBook.get(name)){
  25. numbersList.append(number);
  26. counter++;
  27. if(counter != phoneBook.get(name).size()){
  28. numbersList.append(", ");
  29. }
  30. }
  31. return numbersList.toString();
  32. }
  33. public String reverseLookup(String phoneNumber){
  34. for(Map.Entry<String, List<String>> element: phoneBook.entrySet()){
  35. String key = element.getKey();
  36. List<String> value = element.getValue();
  37. if(value.equals(phoneNumber)){
  38. return key;
  39. }
  40. }
  41. return "This number does not belong to anyone";
  42. }
  43. public void display(){
  44. for(Map.Entry<String, List<String>> element: phoneBook.entrySet()){
  45. String key = element.getKey();
  46. List<String> value = element.getValue();
  47. System.out.println( key + ":" + value);
  48. }
  49. }
  50. }