我正在编写一个程序,它将一系列单词分成标记并读取文本,然后计算它们的频率。此代码有几个相关代码(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 结果。有人帮忙吗?