forked from ChrisMayfield/ThinkJavaCode2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRegularPolygon.java
More file actions
70 lines (60 loc) · 2.07 KB
/
RegularPolygon.java
File metadata and controls
70 lines (60 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import java.awt.Color;
/**
* A polygon that is equiangular (all angles are equal in measure) and
* equilateral (all sides have the same length). It also has a color.
*/
public class RegularPolygon extends DrawablePolygon {
/**
* Constructs a regular polygon, given the number of sides.
*
* @param nsides the number of sides
*/
public RegularPolygon(int nsides) {
this(nsides, 50);
}
/**
* Constructs a regular polygon, given the number of sides and the radius.
*
* @param nsides the number of sides
* @param radius from center to vertex
*/
public RegularPolygon(int nsides, int radius) {
this(nsides, radius, Color.GRAY);
}
/**
* Constructs a regular polygon, given the number of sides, the radius, and
* fill color.
*
* @param nsides the number of sides
* @param radius from center to vertex
* @param color initial fill color
*/
public RegularPolygon(int nsides, int radius, Color color) {
// validate the arguments
if (nsides < 3) {
throw new IllegalArgumentException("invalid nsides");
}
if (radius <= 0) {
throw new IllegalArgumentException("invalid radius");
}
if (color == null) {
throw new NullPointerException("invalid color");
}
// initialize Polygon attributes
this.npoints = nsides;
this.xpoints = new int[nsides];
this.ypoints = new int[nsides];
this.color = color;
// the amount to rotate for each vertex (in radians)
double theta = 2.0 * Math.PI / nsides;
// rotation that makes the polygon right-side up
double rotate = Math.PI / nsides + Math.PI / 2.0;
// compute x and y coordinates, centered at the origin
for (int i = 0; i < nsides; i++) {
double x = radius * Math.cos(i * theta + rotate);
double y = radius * Math.sin(i * theta + rotate);
xpoints[i] = (int) Math.round(x);
ypoints[i] = (int) Math.round(y);
}
}
}