Polygon is a closed curve made up from line segments that join the polygon's corner points. Implement a class Polygon with methods

public double perimeter()

and

public double area()

that compute the circumference and area of a polygon. To compute the perimeter, compute the distance between adjacent points, and total up the distances. The area of a polygon with corners (x0, y0), … , (xn−1, yn−1) is

1/ 2 (x0y0 + x1y1 + ···xn-1y0 - y0x1 - y1x2 - ··· - yn-1x0)

As test cases, compute the perimeter and area of a rectangle and of a regular hexagon. Note: You need not draw the polygon — that is done in Exercise P7.18.

Complete the following files:

Polygon.java

import java.awt.geom.Point2D; import java.util.ArrayList; /** A polygon is a closed curve made up from line segments that join the corner points. */ public class Polygon { . . . /** Constructs a polygon with no corner points. */ public Polygon() { . . . } /** Adds a corner point to the polygon. @param x the x-coordinate of the point @param y the y-coordinate of the point */ public void add(double x, double y) { . . . } /** Calculates the perimeter of a polygon. @return the perimeter of this polygon */ public double perimeter() { . . . } /** Calculates the area of a polygon. @return the area of this polygon */ public double area() { . . . } }

PolygonTester.java

/** This is a tester class for Polygon. */ public class PolygonTester { public static void main(String[] args) { Polygon square = new Polygon(); square.add(100, 100); square.add(100, 150); square.add(150, 150); square.add(150, 100); Polygon hexagon = new Polygon(); // construct a regular hexagon for (int i = 0; i < 6; i++) { double x = . . . double y = . . . hexagon.add(x, y); } double squarePerimeter = square.perimeter(); System.out.println("Square perimeter: " + squarePerimeter); System.out.println("Expected: . . ."); double squareArea = square.area(); System.out.println("Square area: " + squareArea); System.out.println("Expected: . . ."); double hexagonPerimeter = hexagon.perimeter(); System.out.println("Hexagon perimeter: " + hexagonPerimeter); System.out.println("Expected: . . ."); double hexagonArea = hexagon.area(); System.out.println("Hexagon area: " + hexagonArea); System.out.println("Expected: . . ."); } }

PolygonTester2.java