从文本文件创建的字典 - contains() 总是返回 false

我目前正忙于一项小型大学作业,并且在使用我实现的字典类的 contains() 方法时遇到了一些问题 - 该方法总是返回 false。这个类看起来像这样:


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

    }

}

字典从中获取单词的“words.txt”文件可在https://raw.githubusercontent.com/dwyl/english-words/master/words_alpha.txt获得,但这里是它的外观片段:


zinked

zinkenite

zinky

zinkiferous

zinkify

zinkified

zinkifies

zinkifying

zinnia

zinnias

zinnwaldite

zinober

zinsang

zinzar

zinziberaceae

我已经确保“words.txt”中的单词包含在“wordsSet”中,但无法弄清楚为什么 contains 方法对于似乎在 ArrayList 中的单词返回 false。


非常感谢任何帮助。


蓝山帝景
浏览 161回答 2
2回答

喵喔喔

尝试BufferedReader,我尝试并为我工作(我删除了一些无用的行)。在您的使用中,您从文件中读取所有字节,会有额外的字节。public class LocalDictionary {&nbsp; &nbsp; private ArrayList<String> wordsSet = new ArrayList<>();&nbsp; &nbsp; public LocalDictionary() throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; //dont forget to absolute path to here. click righ click to file and copy path&nbsp; &nbsp; &nbsp; &nbsp; File file = new File("C:\\Users\\higuys\\IdeaProjects\\try\\src\\words.txt");&nbsp; &nbsp; &nbsp; &nbsp; BufferedReader br = new BufferedReader(new FileReader(file));&nbsp; &nbsp; &nbsp; &nbsp; String line;&nbsp; &nbsp; &nbsp; &nbsp; while ((line = br.readLine()) != null)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //trim and tolowercase and add to list.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; wordsSet.add(line.trim().toLowerCase());&nbsp; &nbsp; }&nbsp; &nbsp; public boolean contains(String word) {&nbsp; &nbsp; &nbsp; &nbsp; return wordsSet.contains(word.toLowerCase());&nbsp; &nbsp; }}

汪汪一只猫

尝试BufferedReader,我尝试并为我工作(我删除了一些无用的行)。在您的使用中,您从文件中读取所有字节,会有额外的字节。public class LocalDictionary {&nbsp; &nbsp; private ArrayList<String> wordsSet = new ArrayList<>();&nbsp; &nbsp; public LocalDictionary() throws Exception {&nbsp; &nbsp; &nbsp; &nbsp; //dont forget to absolute path to here. click righ click to file and copy path&nbsp; &nbsp; &nbsp; &nbsp; File file = new File("C:\\Users\\higuys\\IdeaProjects\\try\\src\\words.txt");&nbsp; &nbsp; &nbsp; &nbsp; BufferedReader br = new BufferedReader(new FileReader(file));&nbsp; &nbsp; &nbsp; &nbsp; String line;&nbsp; &nbsp; &nbsp; &nbsp; while ((line = br.readLine()) != null)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; //trim and tolowercase and add to list.&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; wordsSet.add(line.trim().toLowerCase());&nbsp; &nbsp; }&nbsp; &nbsp; public boolean contains(String word) {&nbsp; &nbsp; &nbsp; &nbsp; return wordsSet.contains(word.toLowerCase());&nbsp; &nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java