title: Counting frequency of words from a .txt file in java
body: <p>I am working on a Comp Sci assignment. In the end, the program will determine whether a file is written in English or French. Right now, I'm struggling with the method that counts the frequency of words that appears in a .txt file.</p>
  
  <p>I have a set of text files in both English and French in their respective folders labeled 1-20. The method asks for a directory (which in this case is "docs/train/eng/" or "docs/train/fre/") and for how many files that the program should go through (there are 20 files in each folder). Then it reads that file, splits all the words apart (I don't need to worry about capitalization or punctuation), and puts every word in a HashMap along with how many times they were in the file. (Key = word, Value = frequency).</p>
  
  <p>This is the code I came up with for the method:</p>
  
  <pre><code>public static HashMap&lt;String, Integer&gt; countWords(String directory, int nFiles) {
  // Declare the HashMap
  HashMap&lt;String, Integer&gt; wordCount = new HashMap();
  
  // this large 'for' loop will go through each file in the specified directory.
  for (int k = 1; k &lt; nFiles; k++) {
    // Puts together the string that the FileReader will refer to.
    String learn = directory + k + ".txt";
  
  try {
    FileReader reader = new FileReader(learn);
    BufferedReader br = new BufferedReader(reader);
    // The BufferedReader reads the lines
  
    String line = br.readLine();
  
  
    // Split the line into a String array to loop through
    String[] words = line.split(" ");
    int freq = 0;
  
    // for loop goes through every word
    for (int i = 0; i &lt; words.length; i++) {
      // Case if the HashMap already contains the key.
      // If so, just increments the value
  
      if (wordCount.containsKey(words[i])) {         
        wordCount.put(words[i], freq++);
      }
      // Otherwise, puts the word into the HashMap
      else {
        wordCount.put(words[i], freq++);
      }
    }
    // Catching the file not found error
    // and any other errors
  }
  catch (FileNotFoundException fnfe) {
    System.err.println("File not found.");
  }
  catch (Exception e) {
    System.err.print(e);
     }
   }
  return wordCount;
  }
  </code></pre>
  
  <p>The code compiles. Unfortunately, when I asked it to print the results of all the word counts for the 20 files, <a href="https://gist.github.com/anonymous/21a4b5987e1673db882d" rel="nofollow">it printed this</a>. It's complete gibberish (though the words are definitely there) and is not at all what I need the method to do. </p>
  
  <p>If anyone could help me debug my code, I would greatly appreciate it. I've been at it for ages, conducting test after test and I'm ready to give up.</p>