Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.lang.NullPointerException, can't tell why?

I'm writing a program that takes a series of words separated into tokens and reads a text, then counts their frequencies. This code has several related codes (WordCount, FreqStudy, and Echo) but the WordFreq class is what is causing the java.lang.NullPointerException error. Here is my code for 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);
    }
  }
}

And the error I recieve looks like this when I give it a file to read through the FreqStudy main class:

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)

I really don't understand what the issue is and I've been working on this all day so I feel brain dead. Please take a look if you can, I would really appreciate it.

EDIT: I realized that I didn't initialize it right after posting this, but my frequencies return 0 results. Anyone help?

like image 856
Emma Hyde Avatar asked Dec 02 '25 06:12

Emma Hyde


1 Answers

Initialize the array wcArray prior to assigning any values:

wcArray = new WordCount[wordString.length];
like image 62
Reimeus Avatar answered Dec 03 '25 21:12

Reimeus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!