-1

I am working on a little project and have big problem.... I faced the bad side of NullPointerException in Java So here is the code:

  Coordinates[] point = new Coordinates[26];
    for (int i = 0; i < points.length; i++) {
        if (points[i] > 0) {
            char ch = (char) (i + 65);
                point[i].setName(ch);
                point[i].setX(points[i]);
        }
    }
    //Coordinates is class containing 3 fields
    //setName() method just sets Name field
    //setX() method sets X coordinate

I want to make point for every letter in alphabet, but I got NullpointerException when I use setName() method.How can I fix it, please help :(

slimito
  • 5
  • 3

2 Answers2

0

You must instantiate each instance of Coordinates before calling its methods.

    Coordinates[] point = new Coordinates[26];
    for (int i = 0; i < points.length; i++) { 
        if (points[i] > 0) {
            char ch = (char) (i + 65);
                point[i] = new Coordinates();
                point[i].setName(ch);
                point[i].setX(points[i]);
        }
    }
Eran
  • 387,369
  • 54
  • 702
  • 768
0

You're not initializing your Coordinates instances, only the array holding them.

As a result, invoking any method of point[i] throws NullPointerException as it points to a null Coordinates.

You can initialize each Coordinates of point with a new instance:

// some iteration
point[x] = new Coordinates();

Or you can fill the array with the reference to the same instance (probably not what you want):

Arrays.fill(point, new Coordinates());
Mena
  • 47,782
  • 11
  • 87
  • 106