Question

In: Computer Science

i just need the Polygon class Shapes In this lab you will create an interface, and...


i just need the Polygon class

Shapes

In this lab you will create an interface, and then implement that interface in three derived classes.

Your interface will be called Shape, and will define the following functions:

Return Type Name Parameters Description
double area none computes the area of the shape
double perimeter none computes the perimeter of the shape
Point2d center none computes the center of the shape
You will then create 3 implementations of this interface: Rectangle, Circle, and Polygon. Each one will need to provide implementations of area, perimeter, and center. (I have provided an implementation of Square in case you need to reference it.)

Here are the signatures of the constructors for Rectangle, Circle, and Polygon:

// Create a rectangle with p1 and p2 as opposite corners
public Rectangle(Point2d p1, Point2d p2)

// Create a circle with center 'c' and radius 'r'
public Circle(Point2d c, double r)

// Create a polygon with the given points.
public Polygon(Point2d[] pts)
Your classes will need to delare and initialize the necessary instance data to store the necessary data for each class.

Note that I have supplied a Point2d class for you. As you'll see below, this has some functions in it that you may find useful.

I assume you know from HS geometry how to computer the area, perimeter, and center of a rectangle and a circle. It may help to know that the Java library defines pi as Math.pi.

The Polygon class is a bit more complicated:

For the center of the polygon, you can simply average all the x coordinates, and all the y coordinates, then create a point with those averages as the x and y coordinates of the point.
For the perimeter, just use the distance() function in Point2d to compute the length of each edge, and add them.
For the area, I've provided a function in the Point2d class that computes the area of a triangle, given the three points. You can use this function along with the formula Area of a polygon to compute the area of the polygon.
There is one more gotcha in the Polygon class. The Point2d class is immutable (that is, a Point2d object, once created, cannot be modified), but an array is not. One of the tests will fail if you do not take this into account.

I would advise that you use incremental development here. I suggest doing things in this order:

Create the Shape interface. You'll know the Shape interface is correct when the first test passes. (None of the other test will even compile at this point.)
Create the Rectangle class. You'll know this is done correctly when the second test passes. (The other tests will still not even compile.)
Create the Circle and Polygon classes, and have them just pass back dummy data. Once this is done correctly, all the tests should compile, though they will not pass.
Finish the Circle class.
Finish the Polygon class.


// the shape interface with methods which will be implimented in the circle,
//rectangle and polygon class

public interface Shape {
public double area();
public double perimeter();
public Point2d center();
}

public class Point2d {

// NOTE: Point2d is immutable. It is safe to store a reference
// and rely on it not changing.

private double x;
private double y;
public Point2d(double x, double y) {
this.x = x;
this.y = y;
}
public double getX() {
return x;
}

public double getY() {
return y;
}

public double distance(Point2d pt) {
double dx = pt.x - x;
double dy = pt.y - y;
return Math.sqrt(dx*dx + dy*dy);
}
public static double area(Point2d a, Point2d b, Point2d c) {
return ((b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y)) / 2;
}
public String toString() {
return String.format("[%.4f,%.4f]", x, y);
}

public static void main(String[] args) {
// Test distance
{
Point2d p1 = new Point2d(1.0, 1.0);
Point2d p2 = new Point2d(5.0, 4.0);
System.out.println(p1.distance(p2));
System.out.println(p2.distance(p1));
}
// Test area2
{
Point2d p1 = new Point2d(1.0, 1.0);
Point2d p2a = new Point2d(5.0, 1.0);
Point2d p2b = new Point2d(1.0, 4.0);
Point2d p3 = new Point2d(5.0, 4.0);
System.out.println(area(p1, p2a, p3));
System.out.println(area(p1, p2b, p3));
}
}
}


i

Solutions

Expert Solution

Below is the code for all three classes implementing the Shape interface.

Note: I have put all the classes including Point2d in the package named "shapes".

1. Shape.java

package shapes;

interface Shape {

    double area();

    double perimeter();

    Point2d center();

}

2. Rectangle.java

package shapes;

public class Rectangle implements Shape {
    private double length;
    private double breadth;
    private Point2d p1;
    private Point2d p2;

    public Rectangle(Point2d p1, Point2d p2) {
        this.p1 = p1;
        this.p2 = p2;
        this.length = this.p2.getX() - this.p1.getX();
        this.breadth = this.p2.getY() - this.p1.getY();
    }

    public double area() {
        return getLength() * getBreadth();
    }

    public double perimeter() {
        return 2 * (getLength() + getBreadth());
    }

    public Point2d center() {
        double xCenter = (this.p1.getX() + this.p2.getX()) / 2;
        double yCenter = (this.p1.getY() + this.p2.getY()) / 2;
        return new Point2d(xCenter, yCenter);
    }

    public double getLength() {
        return length;
    }

    public double getBreadth() {
        return breadth;
    }

    public void setLength(double length) {
        this.length = length;
    }

    public void setBreadth(double breadth) {
        this.breadth = breadth;
    }
}

3. Circle.java

package shapes;

public class Circle implements Shape {
    private Point2d center;
    private double radius;

    public Circle(Point2d c, double r) {
        this.center = c;
        this.radius = r;
    }

    public double area() {
        return Math.PI * getRadius() * getRadius();
    }

    public double perimeter() {
        return 2 * Math.PI * getRadius();
    }

    public Point2d center() {
        return center;
    }

    public Point2d getCenter() {
        return center;
    }

    public double getRadius() {
        return radius;
    }

    public void setCenter(Point2d center) {
        this.center = center;
    }

    public void setRadius(double radius) {
        this.radius = radius;
    }
}

4. Polygon.java

package shapes;

public class Polygon implements Shape {
    private Point2d[] points;

    public Polygon(Point2d[] pts) {
        this.points = new Point2d[pts.length];
        System.arraycopy(pts, 0, this.points, 0, pts.length); // this method copies the pts array into the points field
                                                              // of the class
    }

    public double area() {

        /*
         * I have used the Shoelace Formula to calculate the area of the polygon
         */
        double xCoordinates[] = new double[points.length];
        double yCoordinates[] = new double[points.length];

        double area = 0.0;

        int j = points.length - 1;
        for (int i = 0; i < points.length; i++) {
            area += (xCoordinates[j] + xCoordinates[i]) * (yCoordinates[j] - yCoordinates[i]);
            j = i;
        }

        return Math.abs(area / 2.0);
    }

    public double perimeter() {
        double perimeter = 0.0;
        for (Point2d pt : points) {
            perimeter += pt.distance(pt);
        }
        return perimeter;
    }

    public Point2d center() {
        double xAvg = 0.0, yAvg = 0.0;
        for (Point2d pt : points) {
            xAvg += pt.getX();
            yAvg += pt.getY();
        }
        double xCenter = xAvg / points.length;
        double yCenter = yAvg / points.length;
        return new Point2d(xCenter, yCenter);
    }
}

NOTE: It would be better if you could provide the test cases for the program. If you can please provide the test cases in the comment to this answer and I will update the answer by running your test cases.
Try to run this program against your test cases and if there is any problem, I will update the answer accordingly.


Related Solutions

Create a class (Shapes) that prompts the user to select a shape to be drawn on...
Create a class (Shapes) that prompts the user to select a shape to be drawn on the screen. Objects: Circle, X, box, box with an x inside, or any other object of your choice. Depending on the user’s choice, you will then ask for the number of rows, columns or any requirements needed to draw the shape. Finally, you will display the shape selected by the user to the screen. Your class should have at least one instance variable. Your...
Create an abstract class polygon that has a method getnoofsides() and getarea() and it has three...
Create an abstract class polygon that has a method getnoofsides() and getarea() and it has three subclasses triangle, rectangle and square each with its own two methods getnoofsides and getarea and their respective implementations accordingly. python
C++ Code (I just need the dieselLocomotive Class) Vehicle Class The vehicle class is the parent...
C++ Code (I just need the dieselLocomotive Class) Vehicle Class The vehicle class is the parent class of the derived class: dieselLocomotive. Their inheritance will be public inheritance so reflect that appropriately in their .h files. The description of the vehicle class is given in the simple UML diagram below: vehicle -map: char** -name: string -size:int -------------------------- +vehicle() +getSize():int +setName(s:string):void +getName():string +getMap():char** +setMap(s: string):void +getMapAt(x:int, y:int):char +~vehicle() +operator--():void +determineRouteStatistics()=0:void The class variables are as follows: map: A 2D array of...
I need an idea on a product for organic chem lab. no particular reactants, just an...
I need an idea on a product for organic chem lab. no particular reactants, just an idea on something to create in lab for a project. it has to be useful. Some of my classmates are making luminol as an example
I NEED TO CREATE A GUI INTERFACE USING TKINTER CONTAINING : Colors, Image, Button, Title bar,...
I NEED TO CREATE A GUI INTERFACE USING TKINTER CONTAINING : Colors, Image, Button, Title bar, and a Menu bar FOR THE QUESTION BELOW: PLEASE HELP PROGRAMMING LANGUAGE IS PYTHON Write a simple quiz game that has a list of ten questions and a list of answers to those questions. The game should give the player four randomly selected questions to answer. It should ask the questions one-by-one, and tell the player whether they got the question right or wrong....
I have this question in my nursing class I just need someone to answer it for...
I have this question in my nursing class I just need someone to answer it for me Reflect on an occasion where you experienced ineffective leadership (doesn't have to be in the hospital/healthcare). What behaviors did they display? What factors may have influenced their leadership style?
In this class add Comparable interface. In the driver program create a few objects and In...
In this class add Comparable interface. In the driver program create a few objects and In the driver program create a few objects and compare them . then create a list of those objects and sort them .A Quadratic is bigger than another Quadratic if it opens faster package pack2; /** * This is a program for defining a quadratic equation * @author sonik */ public class Quadratic { public int coeffX2 = 0; public int coeffX = 0; public...
Both homework are linked. Create a class (Shapes) that prompts the user to select a shape...
Both homework are linked. Create a class (Shapes) that prompts the user to select a shape to be drawn on the screen. Objects: Circle, X, box, box with an x ​​inside, or any other object of your choice. Depending on the user’s choice, you will then ask for the number of rows, columns or any requirements needed to draw the shape. Finally, you will display the shape selected by the user to the screen. Your class should have at least...
(i just need an answer for question 4) (i just need an answer for just question...
(i just need an answer for question 4) (i just need an answer for just question 4) you have two facilities, one in Malaysia and one in Indonesia. The variable cost curve in the Malaysian plant is described as follows: VCM = q­ + .0005*q2 , where q is quantity produced in that plant per month. The variable cost curve in the Indonesian plant is described by VCI = .5q + .00075q2, where q is the quantity produced in that...
Create a concrete LinkedList class that extends the provided ALinkedList class. You will need to override...
Create a concrete LinkedList class that extends the provided ALinkedList class. You will need to override the extract()method in your class. You can use your main() method for testing your method (although you do not need to provide a main method). Recall that a list is an ordered collection of data X_0, X_1, X_2, ..., X_n-1 The extract(int start, int end) method removes all elements X_start, X_start_1, ..., X_end-1 from the list. It also returns all removed elements as a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT