Java - 初始化对象数组列表时出错

时间:2014-03-31 02:19:36

标签: java

当我尝试在代码中使用外围函数时,我得到一个空指针异常。似乎Points数组(Point是一个带有x和y坐标的简单对象)没有正确初始化,我相信我可能错误地声明了数组或构造函数不正确。

package shapes;

import static java.lang.Math.*;

public class Triangle {

private int sides = 3;
private Point[] Points = new Point[sides];

public Triangle(Point[] vertices) {
    vertices = Points;
}

public double perimeter() {
    return Points[0].distance(Points[1]) + Points[1].distance(Points[2]) + Points[2].distance(Points[0]);
}

public double area() {
    double semiperimeter = perimeter() / 2;
    return sqrt(semiperimeter * (semiperimeter - Points[0].distance(Points[1])) * (semiperimeter - Points[1].distance(Points[2])) * (semiperimeter - Points[2].distance(Points[0])));
}

@Override
public String toString() {
    return "Triangle has perimeter of " + perimeter() + " and an area of " + area(); 
}

public void translate(int dx, int dy) {
    for(int i = 0; i < 3; i++) {
        Points[i].translate(dx, dy);
    }
}

public void scale(int factor) {
    for(int i = 0; i < 3; i++) {
        Points[i].scale(factor);
    }        
}

public Point getVertex(int i) {
    return Points[i];
}

}

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:6)

你需要在构造函数中反转它:

vertices = Points;

Points = vertices ;

您需要使用输入Points初始化vertices数组,而不是相反。