简体   繁体   English

计算包含特定术语的文档数量

[英]counting the number of documents containing a specific term

File folder2 = new File("C:\\Users\\user\\fypworkspace\\TextRenderer");

File[] listOfFiles2 = folder.listFiles(); 
System.out.println("Please enter the required word  :");
    Scanner scan2 = new Scanner(System.in); 
    String word2 = scan.nextLine();
    String [] array2 = word2.split(" ");



{
for (int i=0; i < listOfFiles.length; i++)
{
  if ((listOfFiles2[i].getName().endsWith(".txt")))
  {

      try
      {
      BufferedReader in= new BufferedReader(new FileReader(listOfFiles2[i].getName()));

      int numDoc = 0;

      Scanner s2 = new Scanner(listOfFiles2[i].getName());
      {
          while (s2.hasNext())
          {
              if (s2.next().equals(word2)) numDoc++;
          }

            System.out.println("The number of document containing the term is " + numDoc);

        }
        in.close();
    } catch (IOException e) {
    }

This is my code for counting the number of documents that contain a specific term. 这是我的代码,用于计算包含特定术语的文档数量。 Every time the program finds a specific term inside the document, it will increment numDoc counter. 每当程序在文档中找到特定术语时,它将增加numDoc计数器。 This code does not do anything, however. 但是,此代码不执行任何操作。 What am I doing wrong? 我究竟做错了什么?

  1. Add System.out.println() throughout your code to output important information for debugging. 在整个代码中添加System.out.println()以输出重要信息以进行调试。
  2. Not directly related but you can use a enhance for loop to loop through the files. 没有直接关系,但是您可以使用Enhance for循环遍历文件。 See: http://download.oracle.com/javase/tutorial/java/nutsandbolts/for.html 请参阅: http : //download.oracle.com/javase/tutorial/java/nutsandbolts/for.html
  3. Your System.out.println for your total is inside your loop and it should be outside after you have finished looping through all the documents. 总计的System.out.println位于循环中,完成所有文档的循环后,它应该位于循环中。
  4. (And maybe the most important) You are not handling your IOException. (也许是最重要的)您没有处理IOException。 At the least printout a stack trace or the message from the exception. 至少要打印出堆栈跟踪或来自异常的消息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM