0

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;
}
1
  • Show us the stacktrace. On which line are you getting it? Commented Jan 29, 2013 at 6:20

5 Answers 5

12
Gra piece[] = new Gra[10];

does not initialize objects inside the array, it only creates array, so call constructor to create Gras

for (int i = 0; i < piece.length; i++) {
   piece[i] = new Gra();
   piece[i].x = 50;
   piece[i].y = 50;
}
Sign up to request clarification or add additional context in comments.

Comments

3

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.

Comments

1

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;
    }

Comments

0

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.

Comments

0

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;
    }

2 Comments

you do not need two loops to do this.
@tausun yes you are right but i did just for better explanation.

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.