简体   繁体   中英

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. 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.
  2. Not directly related but you can use a enhance for loop to loop through the files. See: 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.
  4. (And maybe the most important) You are not handling your IOException. At the least printout a stack trace or the message from the exception.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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