PolygonTester.java /**
This class creates a polygon object to test the Polygon class.
*/
public class PolygonTester
{
public static void main(String[] args)
{
PolygonTester PolyTest = new PolygonTester();
System.out.println(PolyTest.testPolygon());
System.out.println("Expected: (0,0) (0,10) (10,15)"
+ " (15,10) (10,0) (0,0) ");
}
/**
Creates a polygon and returns a list of the vertices' coordinates
@return list of vertics' coordinates
*/
private String testPolygon()
{
// TODO: Clean up this code by using
// anonymous objects where possible.
Polygon poly = new Polygon(6);
Point startPoint = new Point (0,0);
poly.addPoint(startPoint);
Point secondPoint = new Point(0,10);
poly.addPoint(secondPoint);
Point thirdPoint = new Point(10,15);
poly.addPoint(thirdPoint);
Point fourthPoint = new Point(15,10);
poly.addPoint(fourthPoint);
Point fifthPoint = new Point (10,0);
poly.addPoint(fifthPoint);
poly.addPoint(startPoint);
return poly.listVertices();
}
}
Use the following files:
Point.java
/**
Represents a point on a graph with coordinates (x,y).
*/
public class Point
{
private int x; //the coordinate on the x axis
private int y; //the coordinate on the y axis
public Point(int xCoord, int yCoord)
{
x = xCoord;
y = yCoord;
}
/**
Returns the value of the x-coordinate of the point
@return x-coordinate
*/
public int getX()
{
return x;
}
/**
Returns the value of the y-coordinate of the point
@return y-coordinate
*/
public int getY()
{
return y;
}
}
Polygon.java
/**
This class is the representation of a polygon.
In order to be a full polygon, the end point must be the same as
the original start point.
*/
public class Polygon
{
private Point[] pnts; //stores the points that make up this polygon
private int curPoint; //stores the current point to be added
public Polygon(int numPoints)
{
pnts = new Point[numPoints];
}
/**
Adds a point as a new vertex of the polygon.
@param p a Point object representing a new vertex
*/
public void addPoint(Point p)
{
pnts[curPoint] = p;
curPoint++;
}
/**
Returns the number of elements in the polygon's pnts array
@return size of the pnts array
*/
private int getSize()
{
return pnts.length;
}
/**
Lists the coordinates of the vertices of the polygon
@return list of coordinates
*/
public String listVertices()
{
String pointList = "";
for (int i = 0; i < getSize(); i++)
{
pointList = pointList + "(" + pnts[i].getX()
+ "," + pnts[i].getY() + ") ";
}
return pointList;
}
}