1

I have a object which contains an array of doubles.

public class NumberRow {

static final int MAX_AMOUNT_OF_NUMBERS = 2500;
double[] NumberArray = new double[MAX_AMOUNT_OF_NUMBERS];

NumberRow(double[] NumberArray){
    this.NumberArray = NumberArray;
}

}

In my main program I start with creating a array of the object NumberRow in the constructor like this

NumberRow[] numberRow;

later in the program I put this code:

numberRow = new NumberRow[dataset.numberOfVariables];

After that I call a function which gives value to an numberRow:

double misc = in.nextDouble();
numberRow[k].NumberArray[i] = misc;

I did say where NumberRow is pointing to. However, eclipse gives me a null pointer pointer exception on this line:

numberRow[k].NumberArray[i] = misc;

I hope anyone can see what I did wrong? Thank you :)!

4
  • dataset.numberOfVariables == 0? Commented Jun 5, 2013 at 0:14
  • 2
    These little individual bits of code are very confusing. Please construct a simple, but complete, test-case. Commented Jun 5, 2013 at 0:15
  • double[] NumberArray = new double[MAX_AMOUNT_OF_NUMBERS]; is never used because you reallocate it in the constructor: this.NumberArray = NumberArray;. Are you sure that is what you intended? Commented Jun 5, 2013 at 0:16
  • NumberRow[] numberRow; isn't a constructor. It doesn't "create" anything. Commented Jun 5, 2013 at 0:18

2 Answers 2

1

This is a common mistake I see when beginners start to use arrays of objects. When an array of object references is created, the array is initialized, but the individual elements in the array are null. So, on the statement numberRow[k].NumberArray[i] = misc;, numberRow[k] is null, which is causing the exception. Therefore, before the line, you need to put the statement

numberRow[k] = new NumberRow();

before the above statement.

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

Comments

1

When you do this:

numberRow = new NumberRow[dataset.numberOfVariables];

All of the members of the array numberRow are initialized to the default value of NumberRow. NumberRow is a class, therefore its default value is null. To set values on something that is null, you must first initialize it to a new, real object or you will get a NullPointerException.

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.