首页 > 解决方案 > Dictionary Created from text file - contains() always returns false

问题描述

I am currently busy on a small university assignment and am having some trouble with the contains() method of the dictionary class which I implemented - the method always returns false. The class looks like this:

public class LocalDictionary {
    private ArrayList<String> wordsSet;

    public LocalDictionary() throws IOException {
        String wordListContents = new String(Files.readAllBytes(Paths.get("words.txt")));

        wordsSet = new ArrayList<>();
        String[] words = wordListContents.split("\n");
        for (int i = 0; i < words.length; i++) {
            wordsSet.add(words[i].toLowerCase());
        }
    }

    public boolean contains(String word) {
        return wordsSet.contains(word.toLowerCase());
    }
}

The "words.txt" file from which the dictionary gets its words is available at https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt but here is a snippet of how it looks:

zinked
zinkenite
zinky
zinkiferous
zinkify
zinkified
zinkifies
zinkifying
zinnia
zinnias
zinnwaldite
zinober
zinsang
zinzar
zinziberaceae

I have made sure that the words from "words.txt" are contained in 'wordsSet' but cannot figure out why the contains method returns false for words which appear to be in the ArrayList.

Would appreciate any help immensely.

标签: javalistfiledictionarycontains

解决方案


在添加之前修剪 for 循环中的每一行。行中的每个单词之后似乎都有一些额外的空格。

for (int i = 0; i < words.length; i++) {
    wordsSet.add(words[i].toLowerCase());
}

for (int i = 0; i < words.length; i++) {
    wordsSet.add(words[i].trim().toLowerCase());
}

这可以使用wordsSet.get(1).length(). 根据您的文件,第一行是“aa”,但这会打印 3 而不是 2,这是因为在每个单词之后有一个额外的空格,需要在添加到列表之前进行修剪。

contains()你的方法没有问题。


推荐阅读