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;
                }
jinjan
  • 1
  • 1
    Does this answer your question? [NullPointerException when Creating an Array of objects](https://stackoverflow.com/questions/1922677/nullpointerexception-when-creating-an-array-of-objects) – OH GOD SPIDERS Aug 05 '22 at 09:16

1 Answers1

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.

Stultuske
  • 9,296
  • 1
  • 25
  • 37