我有一个ConvexHull类,必须为我的课程实现。实例变量之一是保存对象Points的数组。
private Points[] points;
当我向构造函数中的数组添加Point时,得到了NullPointerException。
public ConvexHull(int n) throws IllegalArgumentException
{
if (n < 1)
throw new IllegalArgumentException();
else {
Random rand = new Random();
for (int i=0; i<n; i++)
{
int x = rand.nextInt(101)-50;
int y = rand.nextInt(101)-50;
Point p = new Point(x,y);
this.points[i] = p; // NullPointerException is thrown.
this.numPoints = points.length;
}
}
}
基本上,我不知道为什么这不起作用,需要一些帮助。
请为分配内存
private Points[] points;
像这样..
public ConvexHull(int n) throws IllegalArgumentException
{
if (n < 1)
throw new IllegalArgumentException();
else {
points=new Points[n]; //this is the line that is added
Random rand = new Random();
for (int i=0; i<n; i++)
{
int x = rand.nextInt(101)-50;
int y = rand.nextInt(101)-50;
Point p = new Point(x,y);
this.points[i] = p; // NullPointerException is thrown.
this.numPoints = points.length;
}
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句