System.out.println("Please enter the required word :");
Scanner scan2 = new Scanner(System.in);
String word2 = scan2.nextLine();
String[] array2 = word2.split(" ");
for (int b = 0; b < array2.length; b++) {
int numofDoc = 0;
for (int i = 0; i 开发者_如何学编程< filename; i++) {
try {
BufferedReader in = new BufferedReader(new FileReader(
"C:\\Users\\user\\fypworkspace\\TextRenderer\\abc"
+ i + ".txt"));
int matchedWord = 0;
Scanner s2 = new Scanner(in);
{
while (s2.hasNext()) {
if (s2.next().equals(word2))
matchedWord++;
}
}
if (matchedWord > 0)
numofDoc++;
} catch (IOException e) {
System.out.println("File not found.");
}
}
System.out.println("This file contain the term " + numofDoc);
}
}
}
this is my code for calculating number of documents containing a specific term. For example : assume i have 10 million text file and string COW appears in one thousand of these. I am looking for the total one thousand documents containing the COW string.
My program currently only can process one string input.
The output of my program is :
COW
The files containing this term is 1000.
The problem i facing now is when i input 3 strings, It cannot process 3 strings. For example :
COW IS GOOD
The files containing this term is 0.
The files containing this term is 0.
The files containing this term is 0.
I have been trying whole day but i cant see where is my mistake. Mind pointing my mistakes ?
According to your code, you do a loop 3 times (array2.length) but you don't use the array2 at all, instead, you look for the string "COW IS GOOD" three times. you should change the line s2.next().equals(word2)
to s2.next().equals(array2[b])
The problem lies here:
if (s2.next().equals(word2))
if word2 = "I love you"
and you're doing an equals()
, s2.next()
must contain the word I love you
.
One way to solve this.
String[] words = word2.split(" ");
for (String word: words) {
if (s2.next().equals(word)) {
matchedWord++;
}
}
精彩评论