这段代码我一直在假设每次代码在文件中找到一个术语时都要添加一个计数器。计数器表示包含该术语的文档数。
System.out.println("Please enter the required word :");
Scanner scan2 = new Scanner(System.in);
String word2 = scan.nextLine();
String[] array2 = word2.split(" ");
for (int b = 0; b < array.length; b++) {
for (int i = 0; i < filename; i++) {
try {
BufferedReader in = new BufferedReader(new FileReader(
"C:\\Users\\user\\fypworkspace\\TextRenderer\\abc"
+ i + ".txt"));
int numDoc = 0;
int numofDoc = 0;
Scanner s2 = new Scanner(in);
{
while (s2.hasNext()) {
if (s2.next().equals(word2))
numDoc++;
}
}
if (numDoc > 0)
numofDoc++;
System.out.println("File containing the term is "
+ numofDoc);
} catch (IOException e) {
System.out.println("File not found.");
}
输出结果为:
请输入所需的字词:
the
File containing the term is 1
File containing the term is 1
File containing the term is 1
File containing the term is 1
File containing the term is 1
File containing the term is 1
File not found
File containing the term is 1
File containing the term is 1
File containing the term is 1
File containing the term is 1
我希望输出显示包含该术语的文件数为10.
介意指出我的错误?感谢..
答案 0 :(得分:3)
System.out.println("File containing the term is " + numofDoc);
从第二个for
循环中取出(如果您正确缩进代码,则很容易发现这一点)。还要检查您输出的是正确的变量。现在您将结果打印在适当的位置,int numofDoc = 0;
也应位于第二个for
循环之外。
此外,您正在使用String.equals
检查文件的当前行是否包含所需的文本。也许您想查找String.contains
答案 1 :(得分:0)
我猜numDoc
表示文件中出现的次数,numofDoc
代表文件数。
问题是变量int numofDoc = 0
是在for循环中设置的。因此,对于每个新文件,计数器都会重置。
答案 2 :(得分:0)
设置int numDoc = 0;在两个循环之前。
因此,每次执行循环时,您都将值设置为0.
答案 3 :(得分:0)
在for循环之外声明int numDoc = 0; int numofDoc = 0;
。
无论何时执行for循环,他们都会初始化&amp;然后增加到1.这就是你得到所有时间1的原因。
答案 4 :(得分:0)
我想你想这样做
public static void main(String[] args)
{
System.out.println("Please enter the required word :");
Scanner scan2 = new Scanner(System.in);
String word2 = scan.nextLine();
String[] array2 = word2.split(" ");
for ( int b = 0; b < array.length; b++ )
{
**//Declare before the loop**
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++;
System.out.println("File containing the term is " + numofDoc);
}
catch ( IOException e )
{
System.out.println("File not found.");
}
}
}
}