为什么哈希表是空的?

0s7z1bwu  于 2021-06-30  发布在  Java
关注(0)|答案(1)|浏览(407)

我尝试将文本文件中的关键字存储在哈希表中,然后读取另一个具有长字符串的文本文件,将其拆分为单词,将其放入数组中,并循环比较哈希表值与数组值(如果相等或不相等)。
哈希表函数
sysout h值的输出为:

{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}
{}

我在main中用于将文本文件的值与哈希表中的值进行比较的函数是

public static void main(String[] args) throws IOException {
        hash_table keyword = new hash_table();
        String text, t, thisline;
        text = "";
        BufferedReader br = new BufferedReader(new FileReader("words/TextFile.txt"));

        while ((thisline = br.readLine()) != null) {
            if (thisline.length() > 0) {
                text += " " + thisline;
            }
        }
        String[] array = text.split("\\ ", -1);

        int len = array.length;
        for (int i = 0; i < len; i++) {
            t = array[i];
            for (Map.Entry<String, String> entry : keyword.hashtable().entrySet()) {
                if (entry.getValue().equals(t)) {
                    System.out.println("same");

                }
            }
        }
    }

另一件事,当我改变

if (entry.getValue().equals(t)) {

具有

if (!entry.getValue().equals(t)) {

它应该知道的 "same" 但事实并非如此。
我试了好几个小时都没修好,希望有人能帮忙!

xe55xuns

xe55xuns1#

替换此代码

while ((thisline = br.readLine()) != null) { // Will Iterate until br.readLine returns null
    //System.out.println(thisline);
}

while (thisline != null) { // this variable is null, so, this chunk of code is never executed.
    line = br.readLine();
    h.put("" + i, line);
    i++;
}
System.out.println(h); // retrun empty

return h;

用这个

while ((thisline = br.readLine()) != null) {
        h.put("" + i, thisline);
        i++;  
    }
    System.out.println(h);

    return h;

相关问题