Java 使用哈希表检查单词拼写

Java 使用哈希表检查单词拼写,java,string,hashtable,collision,Java,String,Hashtable,Collision,我在哈希表中插入了一个单词数组。 然后是一个函数,它将检查用户键入的单词拼写是否正确。 我的问题是,拼写检查器功能只在我启动单词时起作用,但在用户输入单词(即使拼写正确)时不起作用。 程序是以一种不会发生碰撞的方式设置的,但如果您对如何处理它们有建议,请让我知道 public class hashExample { String[] myArray = new String[31]; public static void main(String[] args) {

我在哈希表中插入了一个单词数组。 然后是一个函数,它将检查用户键入的单词拼写是否正确。 我的问题是,拼写检查器功能只在我启动单词时起作用,但在用户输入单词(即使拼写正确)时不起作用。 程序是以一种不会发生碰撞的方式设置的,但如果您对如何处理它们有建议,请让我知道

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");
            }
    }
}
公共类哈希示例{
字符串[]myArray=新字符串[31];
公共静态void main(字符串[]args){
扫描仪输入=新扫描仪(System.in);
String[]words={“实现”、“跨越”、“显然”、“管理”,
“惊人”、“争论”、“攻击”、“适应”};
hashExample theFunc=新的hashExample();
函数(words,theFunc.myArray);
System.out.println(“输入一个单词以检查拼写…”);
String Word=input.nextLine();
//只有在我启动Word时才有效。
//字符串Word=“容纳”;
芬奇基金会(Word);
}
public void hashFunction(String[]stringsforary,String[]myArray){
对于(int n=0;n
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");
}