java - 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.
解决方案
在添加之前修剪 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()
你的方法没有问题。
推荐阅读
- android - 在 ImageAnalyzer 中绘制画布
- python - JSON 有效负载、AWS Lambda (Python)、API 网关
- javascript - 如何在 Javascript 中放置链接到网页的 PHP 脚本?
- android - WorkManager 未被使用 ExistingPeriodicWorkPolicy.REPLACE 替换
- javascript - 如何在 apidoc 上记录动态对象属性
- asp.net-mvc - 如何解决此错误:System.Data.Entity.Core.EntityCommandCompilationException
- c++ - 如果无关紧要,如何使用模板来收集具有不同参数的函数调用?
- javascript - 使用异步函数返回更多结果
- javascript - 此回文代码仅在 leetcode 中提交时返回错误,它在我的本地用于相同的测试用例
- python - 打印函数'@#%'python