0

I'm new to Java, here's my code so far:

public static MyPoint[] generatePoints(int num) {
    MyPoint[] arr = new MyPoint[num];
    for (int i = 0; i < num; i++) {
        arr[i].x = 1;
        arr[i].y = 1;
    }
    return arr;
}

class MyPoint {
    int x;
    int y;
}

Error:

java.lang.NullPointerException: Cannot assign field "x" because "arr[i]" is null

How can I fix this? What I want is an array of points.

blacktide
  • 10,654
  • 8
  • 33
  • 53
Strella
  • 340
  • 1
  • 9
  • 2
    Unlike C++, you need to initialize objects in an array. On the first line inside your `for` loop, add `arr[i] = new MyPoint();` before accessing the fields. – blacktide Apr 07 '22 at 04:58
  • Thank you. What a pitty that I can't mark that as answer. – Strella Apr 07 '22 at 19:37

0 Answers0