Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //Create a Polygon class. A polygon is a closed shape with lines joining the corner points.
- //You will keep the points in an array list. Use object of java.awt.Point for the point.
- //Polygon will have as an instance variable an ArrayList of Points to hold the points
- //The constructor takes no parameters but initializes the instance variable
- //
- //The add method adds a Point to the polygon
- //
- //The perimeter method returns the perimeter of the polygon
- //
- //The draw method draws the polygon by connecting consecutive points and then
- //connecting the last point to the first.
- //
- //No methods headers or javadoc is provided this time. You get to try your hand at writing a class almost from scratch
- //
- // Need help starting this question? In the lesson titled
- // "Starting points: Problem Set Questions", go to the
- // problem titled "Problem Set 6 - Question 3" for some tips on
- // how to begin.
- //
- import java.util.ArrayList;
- import java.awt.Point;
- public class Polygon
- {
- // TODO: provide the required constructor, instance variable, and methods
- ArrayList<Point> points; // instance variable
- /**
- * Constructor for objects of class ArrayPointsMethods
- */
- public void ArrayPointsMethods(ArrayList<Point> arrayList)
- {
- // initialize instance variables
- points = arrayList;
- }
- /**
- * Add a point to the polygon.
- */
- public void add(Point point)
- {
- points.add(point); // Point newPoint = new Point(x, y); and then points.add(newPoint)
- }
- /**
- * return perimeter of polygon
- */
- public int perimeter()
- {
- int perimeter = 0;
- int x1 = 0;
- int y1 = 0;
- int x2 = 0;
- int y2 = 0;
- for (int i = 0; i <= points.size() ; i++)
- {
- if (i == 0)
- {
- x1 = points.get(i).x;
- y1 = points.get(i).y;
- }
- else if (i == points.size())
- {
- x2 = points.get(0).x;
- y2 = points.get(0).y;
- int distance = (int)Math.sqrt(Math.pow(x2-x1,2) + Math.pow(y2-y1,2));
- perimeter = perimeter + distance;
- }
- else
- {
- x2 = points.get(i).x;
- y2 = points.get(i).y;
- int distance = (int)Math.sqrt(Math.pow(x2-x1,2) + Math.pow(y2-y1,2));
- perimeter = perimeter + distance;
- x1 = x2;
- y1 = y2;
- }
- }
- return perimeter;
- }
- public void draw()
- {
- int x1 = 0;
- int y1 = 0;
- int x2 = 0;
- int y2 = 0;
- for (int i = 0; i <= points.size() ; i++)
- {
- if (i == 0)
- {
- x1 = points.get(i).x;
- y1 = points.get(i).y;
- }
- else if (i == points.size())
- {
- x2 = points.get(0).x;
- y2 = points.get(0).y;
- Line line = new Line(x1, y1, x2, y2);
- line.draw();
- }
- else
- {
- x2 = points.get(i).x;
- y2 = points.get(i).y;
- Line line = new Line(x1, y1, x2, y2);
- line.draw();
- x1 = x2;
- y1 = y2;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement