0

I am getting a null pointer exception when I try to use the perimeter function in my code. It seems that the Points array (Point is a simple object with an x and y coordinate) is not correctly initialising, I believe I may have declared the array wrongly or the constructor is incorrect.

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

}

Any help is much appreciated!

1
  • 1
    You're initializing the array. Are you initializing its elements? Commented Mar 31, 2014 at 2:20

1 Answer 1

6

You need to reverse this in your constructor:

vertices = Points;

to

Points = vertices ;

You need to initialize your Points array with the input vertices and not the other way around.

Sign up to request clarification or add additional context in comments.

2 Comments

So simple, you got it! Thanks haha
@h1h1 it happens..just accept the answer if it helped!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.