Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.*;
- public class PhoneBook
- {
- public static int hashFunction(String name){
- int hash = 0;
- for(int i=0; i<name.length(); i++){
- hash = hash*10 + name.charAt(i);
- }
- hash = hash % 499;
- return hash;
- }
- public static void main(String args[]){
- Hashtable<Integer, String> phonebook = new Hashtable<>();
- List<String> names = new ArrayList<String>();
- Scanner sc = new Scanner(System.in);
- int choice = -1;
- String number;
- String name;
- while(choice != 0){
- System.out.println("What do you want to do?");
- System.out.println("1. Add a contact");
- System.out.println("2. Show a contact");
- System.out.println("3. Delete a contact");
- System.out.println("4. Show all contacts");
- System.out.println("5. Exit");
- choice = sc.nextInt();
- switch(choice){
- case 1:
- System.out.println("Add Phone Number:");
- number = sc.next();
- System.out.println("Name:");
- name = sc.next();
- names.add(name);
- phonebook.put(hashFunction(name), number);
- System.out.println("Added successfully.");
- break;
- case 2:
- System.out.println("Name:");
- name = sc.next();
- number = phonebook.get(hashFunction(name));
- System.out.println("Phone Number: " + number);
- break;
- case 3:
- System.out.println("Name:");
- name = sc.next();
- names.remove(name);
- phonebook.remove(hashFunction(name));
- System.out.println("Removed successfully.");
- break;
- case 4:
- if(phonebook.size() > 0){
- System.out.println(phonebook.size() + " contacts saved");
- for(String i : names){
- System.out.println(i + ": " + phonebook.get(hashFunction(i)));
- }
- }
- else
- System.out.println("You haven't added any contacts yet.");
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment