0

I'm writing a program that will take a text file and determine how many times each word is used in the text file, forming a condensed list. The parameters require me to use two separate classes, as so...

My problem is that nothing is ever added to my Frequency ArrayList, and I can't figure out why exactly. Any help would be much appreciated.

import java.io.File;
import java.util.Scanner;
import java.util.ArrayList;
import java.io.FileNotFoundException;

class FrequencyCounter {

  ArrayList<String> unique;
  ArrayList<Frequency> frequencies;

  public FrequencyCounter(String file) {
    unique = new ArrayList<String>();
    frequencies = new ArrayList<Frequency>();

    try {
      Scanner input = new Scanner(new File(file));
      while (input.hasNextLine()) {
        String[] words = input.nextLine().split(" ");
        for (String word : words) {         // For every word in the line...
          for (Frequency f : frequencies) { // Check every frequency for that word...
            if (f.getWord() == word) {      // If the Frequency already exists...
              f.increment();                // Increment the specific Frequency's counter by one...
            }else{
              frequencies.add(new Frequency (word)); // If no Frequency has this word, make a new one...
            }
          } // End of Frequency for loop
        } // End of String (word) for loop
      } // End of .hasNextLine() while loop
    }catch (FileNotFoundException e){
      e.printStackTrace();
    }
  }

  public static void main(String[] args) {
    FrequencyCounter counter = new FrequencyCounter("sample.txt");
  }
}

class Frequency {

  private String word;
  private int counter;

  public Frequency(String word) {
    this.word = word;
    counter = 1;
  }

  public void increment()  { counter++; };
  public int getCounter() { return this.counter; }
  public String getWord() { return this.word; }
}
  • Did you try stepping through it in a debugger? – Buddy Feb 20 '16 at 05:10
  • `if (f.getWord() == word)` its `if (f.getWord().equals(word))`. – SatyaTNV Feb 20 '16 at 05:11
  • That's not the real problem. The real problem is that it only tries to insert items into `frequencies` while looping over the array itself (which is always empty). – Buddy Feb 20 '16 at 05:13
  • Not sure what you mean. I would've thought that if the ArrayList was initially empty, it'd default to the else statement and make a new entry? –  Feb 20 '16 at 05:16
  • There is no default behavior in a for-loop. Your code says "for each frequency in an empty list"... since the list is empty, the for-loop is skipped. Use a debugger and you would see that. – OneCricketeer Feb 20 '16 at 05:20

0 Answers0