Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class Polygon
- {
- int ncorners = 0;
- Point[] points;
- /**
- Constructs a Polygon object with no corners
- */
- public Polygon()
- {
- points = new Point[0];
- }
- /**
- Adds a point to the list.
- @param p the point to add
- */
- public void add(Point p)
- {
- points = addToArray(points, p);
- ncorners++;
- }
- /**
- Computes the area of a polygon.
- @return area of a polygon
- */
- public double getArea()
- {
- if (ncorners < 3) return 0;
- if (ncorners == 3) {
- return getTriangleSize(points);
- }else {
- Point startingPoint = points[0];
- }
- }
- private double getTriangleSize(Point[] pointArray) {
- //Just making the triangle calculation algorithm easier to type.
- double x1 = pointArray[0].getX();
- double y1 = pointArray[0].getY();
- double x2 = pointArray[1].getX();
- double y2 = pointArray[1].getY();
- double x3 = pointArray[2].getX();
- double y3 = pointArray[2].getY();
- //Algorithm provided by assignment.
- return ((x1*y2) + (x2*y3) + (x3*y1) - (y1*x2) - (y2*x3) - (y3*x1)) / 2;
- }
- private Point[] addToArray(Point[] array, Point newPoint) {
- Point[] point = new Point[array.length + 1];
- for(int i = 0 ; i < array.length; i++) {
- point[i] = array[i];
- }
- point[point.length-1] = newPoint;
- return point;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement