我需要帮助创建一个使用哈希表的小型电话簿应用程序。 这是我的学校作业。我是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 :(得分: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;
}
}