【发布时间】:2018-04-30 04:52:48
【问题描述】:
我有一个单词数组被插入到哈希表中。 然后是一个检查用户输入的单词是否拼写正确的函数。 我的问题是拼写检查功能仅在我启动单词时才起作用,但在用户输入单词时不起作用(即使拼写正确)。 程序的设置方式不会发生冲突,但如果您对如何处理它们有任何建议,请告诉我。
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");
}
}
}
【问题讨论】:
标签: java string hashtable collision