Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.Arrays;
- public class Polygon
- {
- private int ncorners = 0;
- private Point[] points;
- /**
- Constructs a Polygon object with no corners
- */
- public Polygon()
- {
- this.points = new Point[0];
- this.ncorners = 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;
- }
- else if (ncorners == 3) {
- return getTriangleSize(points);
- }else {
- Point startingPoint = points[0];
- Point toDelete = points[1];
- Point toDraw = points[2];
- points = removeFromArray(points, toDelete);
- Polygon p = new Polygon();
- for(Point a : points) {
- p.add(a);
- }
- return getTriangleSize(new Point[]{startingPoint, toDelete, toDraw}) + p.getArea();
- }
- }
- 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();
- double answer = ((x1*y2) + (x2*y3) + (x3*y1) - (y1*x2) - (y2*x3) - (y3*x1)) / 2;
- if(answer < 0) answer = answer * (-1);
- return answer;
- }
- 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;
- }
- private Point[] removeFromArray(Point[] array, Point toRemove) {
- int i, j;
- for (i = j = 0; j < array.length; j++) if (!(toRemove ==array[j])) array[i++] = array[j];
- return Arrays.copyOf(array, i);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement