我正在编写一个程序,该程序需要将一系列单词分成多个标记并读取文本,然后计算其频率。这段代码有几个相关的代码(WordCount,FreqStudy和Echo),但是WordFreq类是导致java.lang.NullPointerException错误的原因。这是我的WordFreq代码:

import java.util.*;
import java.io.*;

public class WordFreq extends Echo{

  WordCount[] wcArray;
  int ct;
  String[] sentence;
  double freq;
  String newLine;

  public WordFreq(String f, String words) throws IOException{
    super(f);
    String[] wordString = words.split(" ");
    for(int i=0; i<wordString.length; i++)
      wcArray[i] = new WordCount(wordString[i]);
    Scanner scan = new Scanner(new FileReader(fileName));
  }

  public void processLine(String line){
    newLine = line.toLowerCase();
    sentence = newLine.split(" ");
    for(String s: sentence){
      for(WordCount w: wcArray){
        if(w.getWord().equals(s))
          w.incCount();
      }
      ct++;
    }
  }

  public void reportFrequencies(){
    for (int i=0; i<wcArray.length; i++){
      freq = (wcArray[i].getCount() / ct);
      System.out.print(wcArray[i].getWord()+" ");
      System.out.printf("%6.4f\n", freq);
    }
  }
}


当我给它一个文件以读取FreqStudy主类时,我收到的错误如下所示:

java.lang.NullPointerException
    at WordFreq.<init>(WordFreq.java:17)
    at FreqStudy.main(FreqStudy.java:14)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at edu.rice.cs.drjava.model.compiler.JavacCompiler.runCommand(JavacCompiler.java:272)


我真的不明白问题是什么,我整天都在努力,所以我感到脑筋急转。如果可以的话,请看一看,非常感谢。

编辑:我意识到我没有发布此后立即初始化,但我的频率返回0结果。有人帮忙吗?

最佳答案

在分配任何值之前初始化数组wcArray

wcArray = new WordCount[wordString.length];

10-07 21:03