Build a simple PhoneBook program.

PhoneBook.java 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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 addNumber(String name, String newNumber){
  16. String checkName = lookup(name);
  17. if(checkName == null){
  18. addEntrant(name, newNumber);
  19. } else {
  20. List<String> newList = new ArrayList<>(phoneBook.get(name));
  21. newList.add(newNumber);
  22. phoneBook.put(name, newList);
  23. }
  24. }
  25. public void removeNumber(String name, String numberToDelete){
  26. String checkName = lookup(name);
  27. if(checkName == null){
  28. System.out.println("User does not exist");
  29. } else {
  30. List<String> newList = new ArrayList<>(phoneBook.get(name));
  31. ListIterator<String> pbIterator = newList.listIterator();
  32. while(pbIterator.hasNext()){
  33. if(pbIterator.next().equals(numberToDelete)){
  34. pbIterator.remove();
  35. }
  36. }
  37. phoneBook.put(name, newList);
  38. }
  39. }
  40. public void removeEntrant(String name){
  41. phoneBook.remove(name);
  42. }
  43. public String lookup(String name){
  44. if (phoneBook.get(name) == null){
  45. return null;
  46. }
  47. StringBuilder numbersList = new StringBuilder();
  48. int counter = 0;
  49. for(String number: phoneBook.get(name)){
  50. numbersList.append(number);
  51. counter++;
  52. if(counter != phoneBook.get(name).size()){
  53. numbersList.append(", ");
  54. }
  55. }
  56. return numbersList.toString();
  57. }
  58. public String reverseLookup(String phoneNumber){
  59. for(Map.Entry<String, List<String>> element: phoneBook.entrySet()){
  60. String key = element.getKey();
  61. for(String number: phoneBook.get(key)){
  62. if(number.equals(phoneNumber)){
  63. return key;
  64. }
  65. }
  66. }
  67. return "This number does not belong to anyone";
  68. }
  69. public void display(){
  70. for(Map.Entry<String, List<String>> element: phoneBook.entrySet()){
  71. String key = element.getKey();
  72. List<String> value = element.getValue();
  73. System.out.println( key + ":" + value);
  74. }
  75. }
  76. }