0

I created an array of 50 points, which I now want to fill with points ordered by their y coordinate in a 10x5 grid. I get a NullPointerException at if(i<5) P[i].x=0. What am I doing wrong here?

  Point[] P= new Point[50]; 
        for (int i=0; i<P.length; i++) {
                if (i<5) P[i].x=0;
                else if (i<10) P[i].x=50;
                else if (i<15) P[i].x=100;
                else if (i<20) P[i].x=150;
                else if (i<25) P[i].x=200;
                else if (i<30) P[i].x=250;
                else if (i<35) P[i].x=300;
                else if (i<40) P[i].x=350;
                else if (i<45) P[i].x=400;
                else P[i].x=450;
            
                if (i%5==0) P[i].y=0;
                else if (i%5==1) P[i].y=50;
                else if (i%5==2) P[i].y=100;
                else if (i%5==3) P[i].y=150;
                else P[i].y=200;
                }
1

1 Answer 1

0
Point[] P= new Point[50]; 
        for (int i=0; i<P.length; i++) {
                if (i<5) P[i].x=0;
                else if (i<10) P[i].x=50;
                else if (i<15) P[i].x=100;
....

Point[] p = new Point[50];

This creates an array which can hold up to 50 instances of the Point class. However, you haven't instantiated any of them, so they're all null.

if (i<5) P[i].x=0;
                    else if (i<10) P[i].x=50;

Depending on the value, you are here trying to set a value to a variable within the instance located at p[i], but that is still null, as explained earlier.

You first need to add actual instances in your array.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.