生成随机数的NullPointerException [重复]

时间:2022-12-15 17:04:56

This question already has an answer here:

这个问题在这里已有答案:

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

我在第14行得到一个NullPointerException:

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);
        }           
    }
}

1 个解决方案

#1


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];它只分配一个有100个点引用空间的数组(它不分配任何Point实例)。您需要先为索引分配一个实例,然后才能访问它,例如

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。

Random rand = new Random();

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

否则你在每次迭代时重新设置(两次)。这意味着你的数字不是很随机。

#1


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];它只分配一个有100个点引用空间的数组(它不分配任何Point实例)。您需要先为索引分配一个实例,然后才能访问它,例如

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。

Random rand = new Random();

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

否则你在每次迭代时重新设置(两次)。这意味着你的数字不是很随机。