We want to design a Java class for representing polygons on the plane, where each polygon is constituted by an ordered sequence of colored vertices.
Part 1. (4 points) For each Vertex object, the information of interest is:
Vertex
, to represent Vertex objects,
that exports the following functionalities:
Solution:
class Vertex
Part 2. (16 points)
Realize a Java class Polygon
, to represent Polygon
objects. Each polygon is constituted by an ordered sequence of colored
vertices, where each vertex is an instance of the class Vertex
and
has a position in the sequence. For a polygon with n vertices, the
positions go from 0 to n-1. A polygon has also a
size, which determines the maximum number of vertices it can have.
The class Polygon
should export the following functionalities:
Vertex
object at position k in the polygon,
if there are at least k+1 vertices in the polygon, throws an
exception otherwise; Vertex
object v,
and a non-negative integer representing a position k, inserts the
vertex v before the vertex at position k in the polygon. The
positions of vertices from k onwards will increase by 1. If k
is not a valid position to insert a new vertex (i.e., there are less than
k vertices in the polygon), an exception is thrown. If the vertex
cannot be inserted because the number of vertices in the polygon is already
equal to its size, an exception is thrown; -1
otherwise; Solution:
representation
of the objects,
skeleton of the class,
class Polygon
,
class
PolygonException
Part 3. (6 points)
Realize a static method coordinatesOfColor
, client of the class
Polygon
(i.e., external to such a class) that, given a
Polygon
object pol, a string c representing a
color, and the name f of a file, writes on the file f the
x and y coordinates of all those vertices of pol that
have color c, one pair of coordinates per line. The method should
handle exceptions due to input/output errors that may occur.
Additional files to test the solution:
class Main
,
input file
vertices.txt
Part 4. (4 points) Discuss the mechanism of dealing with errors in Java through exceptions. Give a complete example, where you show how a class for handling exceptions is defined, how an exception is thrown, and how an exception is handled by catching it.