0

I'm getting a NullPointerException and after doing research I can't figure out why. The error message reads:

java.lang.NullPointerException
    at TextDecoder.readMessagesFromFile(TextDecoder.java:32)
    at TextDecoder.main(TextDecoder.java:54)

I've commented next to lines 54 and 32.

This is my constructor (all of these methods come from the same class):

  public TextDecoder() {
        messages = new TextMessage[10];
        msgCount = 0;
      }

My Main method is the following (I included class declaration):

public class TextDecoder {
public static void main(String[] args) throws Exception {

    if (args.length != 1) {
      System.out.println("There is an incorrect amount of command-line arguments. Command-line Argument length: " + args.length);
      System.exit(1);
    } 
    File msgFile = new File(args[0]);
    if (msgFile == null) {
      System.out.println("File not found.");
      System.exit(1);
    }
    readMessagesFromFile(msgFile); // Line 32
}
}

My readMessagesFromFile is the following:

public static void readMessagesFromFile(File inputMsgFile) throws Exception {

Scanner input = new Scanner(inputMsgFile);

 while (input.hasNextLine()) {

   /* Some code here */
// Recipient and keyPresses are defined in here and are not null

   }
   messages[msgCount] = new TextMessage(recipient, keyPresses); // Line 54
   msgCount++;
 }
 input.close();
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
Dave Jha
  • 55
  • 5
  • 2
    Possible duplicate of [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Lorelorelore Oct 02 '18 at 15:26
  • Please post a [mcve], you are leaving out essentially pieces of your code. It looks like `messages` is `static`, if so it is likely wrong to initialize it from the `TextDecoder` constructor; or it indicates that `messages` **should not** be `static`. – Mark Rotteveel Oct 02 '18 at 15:34

1 Answers1

3
public TextDecoder() {
    messages = new TextMessage[10];
    msgCount = 0;
  }

This is a constructor, which is invoked with new TextDecoder().

You don't invoke this, so messages is never initialized. (But you shouldn't be setting static fields in a constructor anyway).

Either make the readMessagesFromFile method an instance method (remove the static; and create an instance of TextDecoder on which to invoke the method); or initialize the state statically.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243