我一直在执行此代码,假设每次代码在文件中找到术语时都添加一个计数器。计数器代表包含该术语的文档数。

    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。

介意指出我的错误?谢谢..

最佳答案

正确缩进代码(在Eclipse下,CTRL + SHIFT + F将为您完成代码)
给您的变量明智的名称。 numDoc和numOfDoc太近了,以免发生错误
您正在内部循环中输出计数器,请尝试使您的System.out.println("File containing the term is " + numofDoc);脱离第二个for循环(如果正确缩进代码,很容易发现这一点)。还要检查您是否正在输出正确的变量。




现在,您将结果打印在正确的位置,int numofDoc = 0;也应位于第二个for循环之外。

此外,您正在使用String.equals检查文件的当前行是否包含必需的文本。也许您想查找String.contains的文档

10-07 23:28