0

I'm learning arrays for the first time and have been unable to figure out why i keep getting errors. This is my constructor for my class called Grades.

public Grades(float [] g){
    for(int i = 0; i < g.length; i++){
        if(g[i] >= 0 && g[i] <=100){

            listOfGrades[i] = g[i];

        }

    }
}

From my understanding this should run through each index of the array in this case the object was tested as:

float[] a = {70, 60, 80,90,100};
Grades allQuizGrades = new Grades(a);

Why do i get a null pointer exception?

2 Answers2

2

Have a look at this What is a NullPointerException, and how do I fix it?

In short, a null pointer exception generally means that you are trying to access part of a data structure that has no reference in memory. In this example, it's just down to the fact that you haven't initialised the array properly.

Array initialisation in Java looks like this

DATA_TYPE[] name = new DATA_TYPE[ARRAY_SIZE];

When calling for this in a class, you'll want to have the first half with your private variables and the second half declared in the constructor when you know how large you want the array to be. So this will appear before the constructor with the private variables:

private DATA_TYPE name;

And this will appear in your constructor:

name = new DATA_TYPE[ARRAY_SIZE];
Community
  • 1
  • 1
1

Just copy the array directly:

public Grades(float [] g){
    listOfGrades = Arrays.copyOf(g);
}

I'm guessing you just declared float[] listOfGrades. You need to actually instantiate it if you don't want an array copy:

public Grades(float [] g){
    listOfGrades = new float[g.length];
    for(int i = 0; i < g.length; i++){
        if(g[i] >= 0 && g[i] <=100){

            listOfGrades[i] = g[i];

        }

    }
}
nanofarad
  • 40,330
  • 4
  • 86
  • 117