gpt4 book ai didi

java - 使用哈希表的电话簿

转载 作者:太空宇宙 更新时间:2023-11-04 12:38:09 24 4
gpt4 key购买 nike

我需要帮助创建一个使用哈希表的小型电话簿应用程序。这是我的学校作业。我对 Java 很陌生,所以我无法真正理解这一点。

我对应用程序如何运行有一个基本的代码布局,但我只是不知道如何实现哈希表。

我不允许使用Java中内置的数据结构,所以我必须从头开始构建哈希表。不过,我可以使用哈希表的 native 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
}

}

最佳答案

对于将其发布为答案,我深表歉意。我不知道如何添加带有添加代码的评论。

编辑:我找出了多值。我现在的问题是删除具有相同索引/散列键的条目。例如。有三个值具有相同的键,我可以删除第一个和第二个值,但不能删除第三个。

这是我的代码:

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;
}
}

关于java - 使用哈希表的电话簿,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37104587/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com