Search code examples
javadata-structureshashtable

Why hashtable is empty?


I am trying to store keywords from text file in a hashtable then read another text file with a long string, split it into words, put it in an array, and loop to compare the hashtable values with the array values if equals or not.

hash table function

The output of sysout h value is:

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

The fucntion i use in main to compare the values of text file with the values in the hashtable is

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");

                }
            }
        }
    }

another thing, when i change

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

with

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

which it should sysout "same" but it didn't.

I was trying for hours to fix it without success, hope someone can help!


Solution

  • Replace this code

    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;
    

    With this

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