Question
(Java) (a) Write the missing constructor for the Polygon class below. Hint, you need to make sure each Polygon has its OWN array of Point
(Java)
(a) Write the missing constructor for the Polygon class below. Hint, you need to make sure each Polygon has its OWN array of Point and isnt sharing that array with another Polygon. You also need to make sure the points are not also shared between two arrays. Your code must work for any number of points, not just with 3 as shown in the example. Use the Point class shown on the screen.5.
(b) Add the missing contains() method to Polygon so that PolygonTest works as indicated by the comments. Assume the Point class includes the equals() method from problem 3.
class PolygonTest {
public static void main(String[] args) {
Point[] points={new Point(10,20), new Point(10,40), new Point(40,40)};
Polygon p1 = new Polygon(points);
Polygon p2 = new Polygon(points);
p1.translate(5,6);
System.out.println(p1); // prints "(15,26) (15,46) (45, 46)"
System.out.println(p2); // prints "(10,20) (10,40) (40, 40)"
System.out.println(p2.contains(new Point(10,40))); // prints true
System.out.println(p2.contains(new Point(40,50))); // prints false
}
}
class Polygon {
private Point[] theArray;
Polygon(Point[] array) {
// missing code goes here for part a
}
public String toString() {
String result = "";
for (int i = 0; i < theArray.length; i++) {
result = result + theArray[i] + " ";
}
return result;
}
void translate(int dx, int dy) {
for (int i = 0; i < theArray.length; i++) {
theArray[i].translate(dx,dy);
}
}
// missing code goes here for part b
class Point {
int x, y;
Point(int x, int y) {
this.x = x;
this.y = y;
}
void translate(int dx, int dy) {
x = x + dx;
y = y + dy;
}
public String toString() {
return "(" + x + "," + y + ")";
}
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started