2015-04-06 35 views
2

我有一个类ConvexHull,我必须为我的类实现。其中一个实例变量是一个包含对象Points的数组。添加对象到数组并获取NullPointerException

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

基本上,我不知道为什么这不工作,需要一些帮助。

回答

0

请为

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

因为您没有实例化数组points。你需要像

private Point[] points = new Point[i]; 

其中我是一个整数指定数组的长度。否则pointsnullNullPointerException被抛出。

顺便说一句,我不认为有一个类叫Points。如果你创建自己的类(实际上你可能不需要),不要用复数名词来命名它。

0

呀你的代码的问题是,你需要声明数组,但你有没有像初始化

数组
points = new Point[sizeOfYourArray]; 

它应该解决您的问题,因为在冷杉中没有任何东西可以开始所以当你初始化它时应该没问题。

0

你没有新的像pointer p = new pointer();这样的字段“指针”的对象,所以你会得到一个NullPointerException。