2016-05-08 46 views
1

我需要幫助創建一個使用散列表的小型電話簿應用程序。 這是給我的作業。我對Java很陌生,所以我不能真正理解這一點。使用散列表的電話簿

我有一個應用程序如何運作的代碼的基本佈局,我只是丟失如何實現散列表。

我不允許使用Java中內置的數據結構,所以我必須從頭開始構建哈希表。但是,我可以使用散列表的本地hashCode()函數。

這裏是我的代碼,並在它的一些注意事項:

import java.util.Scanner; 

public class PhoneBook { 

public static void main(String[] args) { 

    boolean exitPhoneBook = false; 
    Scanner userInput = new Scanner(System.in); 

    while (exitPhoneBook == false) { 

     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"); 
     System.out.print("Select a number: "); 

     int action = userInput.nextInt(); 

     switch (action){ 
     case 1: 
      addContact(); 
      break; 

     case 2: 
      showContact(); 
      break; 

     case 3: 
      deleteContact(); 
      break; 

     case 4: 
      showAll(); 
      break; 

     case 5: 
      System.out.println("Goodbye!"); 
      exitPhoneBook = true; 
      break; 

     default: 
      System.out.println("Invalid option."); 
      System.out.print("Select a number: "); 
      break; 
     } 
    } 

} 

static void addContact(){ 
    //takes in four strings from user (first name, last name, phone number, email) 
} 

static void showContact(){ 
    //takes in two strings from user (first name, last name) 
} 

static void deleteContact(){ 
    //takes in two strings from user (first name, last name) 
} 

static void showAll(){ 
    //prints out all the contact in the hash table 
} 

} 
+0

那麼,什麼是問題? – Mureinik

+0

構建散列表的另一個類。不要在你的「電話簿」課上這樣做。 – SevenBits

+1

一些靈感鏈接:[Java哈希表實現](https://codereview.stackexchange.com/questions/24116/hash-table-implementation-in-java)[Java如何實現哈希表?](https:/ /stackoverflow.com/questions/1647221/how-does-java-implement-hash-tables) – SevenBits

回答

0

我張貼此作爲一個答案道歉。我不知道如何添加添加代碼的評論。

編輯:我想出了多值。我現在的問題是刪除具有相同索引/散列鍵的條目。例如。有三個值具有相同的密鑰,我可以刪除第一個和第二個值,但不能刪除第三個值。

這裏是我爲它的代碼:

public void deleteContact(String key) { 
    int location = hashFunction(key); 
    if (contactsArray[location] == null) { //if the contact doesn't exist 
     System.out.println("Contact not found.\n"); 
     return; 
    } 

    if (contactsArray[location].key.equals(key)) { 
     contactsArray[location] = contactsArray[location].next; //if contact is on first item 
     System.out.println("Contact has been removed\n"); 
     return; 
    } 

    //If contact is not the first item of the same key 
    ContactList prev = contactsArray[location]; 
    ContactList curr = prev.next; 
    while (curr != null && ! curr.key.equals(key)) { 
     curr = curr.next; 
     prev = curr; 
    } 

    if (curr != null) { 
     prev.next = curr.next; 
     System.out.println("Contact has been removed"); 
     return; 
    } 
}