用户选择一个文本文件。我将文件中的 1 行拆分为单独的单词。然后,我使用 if 语句来查看其中一个单词是否等于单词“the”。第一行中有“the”这个词,但它并没有说有。它正在拾取其他“the”,只是不是第一个(是的,我知道这是一团糟,但这就是我正在处理的目前)
try {
BufferedReader br = new BufferedReader(new FileReader(test));
//String text = "";
String line = br.readLine();
//while (line != null)
if(line != null) {
for(int j = 0; j < 20; j++) //loops through first 20 lines {
if(line != null) {
//text += line;
String[] words = line.toLowerCase().split(" ");
for(int i = 0; i < words.length; i++){//loops array of split up words
if(words[i].equals("the")) {
System.out.println("Found T H E");
} else {
System.out.println("Didn't find the");
System.out.println(words[i]);
}
line = br.readLine();
}
} else {
System.out.println("");
}
}
} else {
System.out.println("It's null");
}
br.close();
} catch (Exception ex) {
System.err.println("Error" + ex);
}
最佳答案
尝试移动线条
line = br.readLine();
在循环之外
for(int i = 0; i < words.length; i++){
关于java - 一次读入文本文件 1 行并将单词拆分为 Array Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47663413/