【发布时间】:2018-01-29 20:56:01
【问题描述】:
我有一个字符串数组,其中包含一首故意拼写错误的诗。我试图通过将字符串数组与包含字典的字符串数组进行比较来遍历字符串数组以识别拼写错误。如果可能的话,我想要一个允许我继续使用嵌套 for 循环的建议
for (int i = 0; i < poem2.length; i++) {
boolean found = false;
for (int j = 0; j < dictionary3.length; j++) {
if (poem2[i].equals(dictionary3[j])) {
found = true;
break;
}
}
if (found==false) {
System.out.println(poem2[i]);
}
}
输出会打印出拼写正确的单词以及拼写错误的单词,我的目标是只打印出拼写错误的单词。以下是我填充“dictionary3”和“poem2”数组的方法:
char[] buffer = null;
try {
BufferedReader br1 = new BufferedReader(new
java.io.FileReader(poem));
int bufferLength = (int) (new File(poem).length());
buffer = new char[bufferLength];
br1.read(buffer, 0, bufferLength);
br1.close();
} catch (IOException e) {
System.out.println(e.toString());
}
String text = new String(buffer);
String[] poem2 = text.split("\\s+");
char[] buffer2 = null;
try {
BufferedReader br2 = new BufferedReader(new java.io.FileReader(dictionary));
int bufferLength = (int) (new File(dictionary).length());
buffer2 = new char[bufferLength];
br2.read(buffer2, 0, bufferLength);
br2.close();
} catch (IOException e) {
System.out.println(e.toString());
}
String dictionary2 = new String(buffer);
String[] dictionary3 = dictionary2.split("\n");
【问题讨论】:
-
我复制了您的代码并尝试了数组
String[] poem2 = new String[]{"test", "asdf"};和String[] dictionary3 = new String[]{"apple", "banana", "test"};,并且只正确收到了值asdf。也许你的字典有问题? -
我无法重现您的问题。它只为我打印不正确的单词ideone.com/TghyDx
-
但这就是您的代码所做的与您在“输出打印出正确拼写的单词以及拼写错误的单词”中所声称的相反。如果您在正确的minimal reproducible example(又名SSCCE)后没有得到预期的结果。此外,“我的字典是一个 txt 文件”并没有告诉我们太多,因为
dictionary3看起来不像File实例,而是像String[]数组。您可能声称该数组应该填充文本文件的内容,但它不是文本文件,也不是有关其位置的信息。 -
@Keara 我已经编辑了我的帖子,代码显示了我在哪里初始化我的 dictionary3 和poem2 变量
-
@Pshemo 我编辑的帖子是否为您提供了更多说明?抱歉,不清楚。
标签: java arrays string loops nested-loops