gpt4 book ai didi

java - 使用哈希表检查单词的拼写

转载 作者:行者123 更新时间:2023-12-02 12:00:04 26 4
gpt4 key购买 nike

我有一个单词数组被插入到哈希表中。然后是一个函数来检查用户输入的单词是否拼写正确。我的问题是,拼写检查器功能仅在我启动该单词时才起作用,但如果用户输入该单词(即使拼写正确)则不起作用。程序的设置方式不会发生冲突,但如果您对如何处理冲突有建议,请告诉我。

public class hashExample {

String[] myArray = new String[31];

public static void main(String[] args) {

Scanner input = new Scanner(System.in);

String[] words = { "Achieve", "Across", "Apparently", "Admin",
"Amazing", "Argument", "Assasination", "Accommodate" };

hashExample theFunc = new hashExample();

theFunc.hashFunction(words, theFunc.myArray);

System.out.println("Enter a word to check for spelling...");

String Word = input.nextLine();
//Works only if I initiate Word.
//String Word = "Accommodate";

theFunc.findKey(Word);
}

public void hashFunction(String[] stringsForArray, String[] myArray) {

for (int n = 0; n < stringsForArray.length; n++) {

String newElementVal = stringsForArray[n];

// Using ASCII values of the first four letters of each word.
int arrayIndex = ((int)newElementVal.charAt(0) + (int)newElementVal.charAt(1)
+ (int)newElementVal.charAt(2)+ (int)newElementVal.charAt(3)) % 31;

myArray[arrayIndex] = newElementVal;
}
}

public void findKey(String key) {

int indexHash = ((int)key.charAt(0) + (int)key.charAt(1) + (int)key.charAt(2)
+ (int)key.charAt(3)) % 31;

String wordSearch = myArray[indexHash];

if (key == wordSearch){
System.out.println("Word is spelled correctly!");
} else{
System.out.println("Sorry word is not spelled correctly");
}
}
}

最佳答案

key == wordSearch 更改为 key.equals(wordSearch),然后它将开始处理输入。

因为字符串是对象,如果要比较两个字符串,请使用 .equals 方法而不是 == 来比较它们。

if (key.equals(wordSearch)) {
System.out.println("Word is spelled correctly!");
} else {
System.out.println("Sorry word is not spelled correctly");
}

关于java - 使用哈希表检查单词的拼写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47333247/

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