ArrayList返回null,不知道为什么

时间:2016-02-20 05:09:48

标签: java arraylist

我正在编写一个程序,该程序将采用文本文件并确定文本文件中每个单词的使用次数,从而形成一个精简列表。参数要求我使用两个单独的类,如此......

我的问题是我的频率阵列列表中没有添加任何内容,我无法弄清楚原因。任何帮助将不胜感激。

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; }
}

0 个答案:

没有答案