Reputation: 17
Hi there i'm creating a small game for school, but when i try to do this to fill out the x and y variables in this array i get a NPE. Could anyone help?
public class mainclass {
public static void main(String[] args) {
Gra piece[] = new Gra[10];
for (int i = 0; i < piece.length; i++) {
piece[i].x = 50;
piece[i].y = 50;
}
}
}
class Gra{
public int x = 50;
public int y = 10;
}
Upvotes: 0
Views: 1023
Reputation: 41220
You have initialized gra array
but you did not create Object
so there is no Object inside the array and by default null is initialized, so piece[i].x
is actually null.x
which throws NPE.
Gra piece[] = new Gra[10];
for (int i = 0; i < piece.length; i++) {
piece[i] = new Gra();
piece[i].x = 50;
piece[i].y = 50;
}
Upvotes: 1
Reputation: 2555
The statement
Gra piece[] = new Gra[10];
will only initialize the array. It won't create Gra
objects.
Inside the for loop
, you still have to call the constructor as
for (int i = 0; i < piece.length; i++) {
piece[i] = new Gra();
piece[i].x = 50;
piece[i].y = 50;
}
Also, read more about encapsulation
. Its a bad idea
to make instance variables public
.
Upvotes: 3
Reputation: 15896
Because you are just creating Array of type Gra
By
Gra piece[] = new Gra[10];
So by default this is null
.
So first initialize them like
for (int i = 0; i < piece.length; i++) {
pirce[i] = new Gra();
}
Then do
for (int i = 0; i < piece.length; i++) {
piece[i].x = 50;
piece[i].y = 50;
}
Upvotes: 0
Reputation: 21893
You have created a an array of Gra with 10 elements.
Gra piece[] = new Gra[10];
But each element in that array is currently pointing to null.
You need to initialize those individual elements as Java's default value for Object is null.
Upvotes: 0
Reputation: 9579
Gra piece[] = new Gra[10];
does not initialize objects inside the array, it only creates array, so call constructor to create Gra
s
for (int i = 0; i < piece.length; i++) {
piece[i] = new Gra();
piece[i].x = 50;
piece[i].y = 50;
}
Upvotes: 12