我目前正在编写一个程序,要求我检查数组中的单词,对照文本文件(字典)中的所有单词,如果是,则返回值true,如果不是,则返回false 。 到目前为止,这是我的代码
public static boolean isEnglishWord(String[] arrayOfWords) throws IOException {
for (String line : Files.readAllLines(Paths.get("words.txt"), StandardCharsets.UTF_8)) {
if(arrayOfWords[0] == line)
{
return true;
}
else
{
return false;
}
}
return false;
}
我知道这只会检查'行中的第一个单词,我想知道如何移动到下一个单词以将其与数组中的单词进行比较
答案 0 :(得分:4)
删除此部分:
public static boolean isEnglishWord(String[] arrayOfWords) throws IOException {
for (String line : Files.readAllLines(Paths.get("words.txt"), StandardCharsets.UTF_8)) {
if(arrayOfWords[0].equals(line)) // use `equals()` instead of `==`
{
return true;
}
// else --> If word is not found, you will eventually return false
// {
// return false;
// }
}
return false;
}
答案 1 :(得分:2)
除了以明显的方式修复代码之外,您还可以考虑升级到Java 8习语:
return Files.lines(Paths.get("words.txt"), UTF_8)
.anyMatch(w1 -> Stream.of(arrayOfWords)
.anyMatch(w2 -> w2.equals(w1)));
此外,将O(n 2 )算法转换为O(n)的典型优化是使用Set<String>
而不是字符串数组:
final Set<String> setOfWords = new HashSet<>(Arrays.asList(arrayOfWords));
然后你写
return Files.lines(Paths.get("words.txt"), UTF_8)
.anyMatch(setOfWords::contains);
或者,如果空间是一个问题,您可以只对数组进行排序并在其上使用JDK提供的二进制搜索,从而导致O(n log n)复杂度:
Arrays.sort(arrayOfWords);
和
return Files.lines(Paths.get("words.txt"), UTF_8)
.anyMatch(w -> Arrays.binarySearch(arrayOfWords, w) >= 0);
最后,看起来你真正要检查的是 all 文件中的单词是英文单词,而不是文件中至少包含一个这样的单词。经过上述重构后,逻辑非常清晰,现在很容易通过替换两个字符来改变:
return Files.lines(Paths.get("words.txt"), UTF_8)
.allMatch(setOfWords::contains);
...这是一个很好的演示,说明FP成语的简洁性如何使您的代码更加明显,更容易调试。
答案 2 :(得分:0)
首先在比较字符串时使用equals
。其次,使用嵌套循环:
public static boolean isEnglishWord(String[] arrayOfWords) throws IOException {
for (String line : Files.readAllLines(Paths.get("words.txt"), StandardCharsets.UTF_8)) {
for (String word : arrayOfWords) {
if(word.equals(line))
{
return true;
}
}
}
return false;
}
这假设您的方法只需要将整个文件中的单个单词与数组中的单个单词匹配,以便返回true。我不确定这种方法有多么有用。
答案 3 :(得分:0)
您只是检查arrayOfWords中的第一个单词。您需要两个循环才能检查文件中的所有单词与arrayOfWords中的所有单词。
public static boolean isEnglishWord(String[] arrayOfWords) throws IOException {
for (String line : Files.readAllLines(Paths.get("words.txt"), StandardCharsets.UTF_8)) {
for (String word: arrayOfWords)
return word.equalsIgnoreCase(line);
}
return false;
}