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();
2

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.