Guest User

Untitled

a guest
Jun 22nd, 2021
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.44 KB | None | 0 0
  1. import java.util.*;
  2.  
  3. public class PhoneBook
  4. {
  5. public static int hashFunction(String name){
  6. int hash = 0;
  7. for(int i=0; i<name.length(); i++){
  8. hash = hash*10 + name.charAt(i);
  9. }
  10. hash = hash % 499;
  11. return hash;
  12. }
  13.  
  14. public static void main(String args[]){
  15. Hashtable<Integer, String> phonebook = new Hashtable<>();
  16. List<String> names = new ArrayList<String>();
  17. Scanner sc = new Scanner(System.in);
  18.  
  19. int choice = -1;
  20. String number;
  21. String name;
  22.  
  23. while(choice != 0){
  24. System.out.println("What do you want to do?");
  25. System.out.println("1. Add a contact");
  26. System.out.println("2. Show a contact");
  27. System.out.println("3. Delete a contact");
  28. System.out.println("4. Show all contacts");
  29. System.out.println("5. Exit");
  30. choice = sc.nextInt();
  31.  
  32. switch(choice){
  33. case 1:
  34. System.out.println("Add Phone Number:");
  35. number = sc.next();
  36. System.out.println("Name:");
  37. name = sc.next();
  38. names.add(name);
  39. phonebook.put(hashFunction(name), number);
  40. System.out.println("Added successfully.");
  41. break;
  42. case 2:
  43. System.out.println("Name:");
  44. name = sc.next();
  45. number = phonebook.get(hashFunction(name));
  46. System.out.println("Phone Number: " + number);
  47. break;
  48. case 3:
  49. System.out.println("Name:");
  50. name = sc.next();
  51. names.remove(name);
  52. phonebook.remove(hashFunction(name));
  53. System.out.println("Removed successfully.");
  54. break;
  55. case 4:
  56. if(phonebook.size() > 0){
  57. System.out.println(phonebook.size() + " contacts saved");
  58. for(String i : names){
  59. System.out.println(i + ": " + phonebook.get(hashFunction(i)));
  60. }
  61. }
  62. else
  63. System.out.println("You haven't added any contacts yet.");
  64. }
  65. }
  66. }
  67. }
Advertisement
Add Comment
Please, Sign In to add comment