-1

I get a NullPointerException at line 14 the one that says:

points[i].x = new Random().nextInt(30);

My full Code:

import java.util.Random;

public class RandomPoints {
    public class Point {
         public int x;
         public int y;
    }

    public static void main(String[] args) {
        Point[] points = new Point[100];
        for(int i = 0; i < points.length; i++) {
            points[i].x = new Random().nextInt(30);
            points[i].y = new Random().nextInt(30);
            System.out.println(points[i].x + " " + points[i].y);
        }           
    }
}
ketan
  • 19,129
  • 42
  • 60
  • 98
cat000
  • 35
  • 5

1 Answers1

1

When you say Point[] points = new Point[100]; it only allocates an array with room for 100 Point references (it doesn't allocate any Point instances). You need to allocate an instance for the index before you can access it, something like

Point[] points = new Point[100];
for(int i = 0; i < points.length; i++) {
    points[i] = new Point(); //<-- like so.

Also, it would be better to reuse one Random created outside your array.

Random rand = new Random();

otherwise you reseed (twice) on every iteration. Meaning your numbers won't be very random.

Elliott Frisch
  • 198,278
  • 20
  • 158
  • 249