【问题标题】:Why hashtable is empty?为什么哈希表是空的?
【发布时间】:2021-03-20 02:47:19
【问题描述】:

我正在尝试将文本文件中的关键字存储在哈希表中,然后读取另一个带有长字符串的文本文件,将其拆分为单词,将其放入数组中,然后循环以将哈希表值与数组值进行比较,如果等于或不是。

哈希表函数

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)) {

它应该 sysout "same" 但它没有。

我试了好几个小时都没有成功,希望有人能帮忙!

【问题讨论】:

    标签: java data-structures hashtable


    【解决方案1】:

    替换此代码

    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;
    

    【讨论】:

    • @Mohamed 很棒。因此,请为答案投票,并接受它作为正确答案。这将帮助我,并将帮助网站更清洁。
    • 是的,我只是在等待 3 分钟才能接受它作为正确答案,而要获得支持,我需要至少 15 个代表分数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 2020-07-28
    相关资源
    最近更新 更多