In an n-sided regular polygon, all sides have the same length and all angles hav
ID: 3598825 • Letter: I
Question
In an n-sided regular polygon, all sides have the same length and all angles have the same degree (i.e., the polygon is both equilateral and equiangular). Design a class named RegularPolygon that contains: Aprivate int data field named n that defines the number of sides in the polygon (the default value is 3). a. b. Aprivate double data field named side that stores the length of the side (the default value is 1) c. Apublic no-argument constructor that creates a regular polygon with default values for the number of sides and side length. d. Apublic constructor that creates a regular polygon with the specified number of sides and length of side public accessor ("getter") and mutator ("setter") methods for all data fields. Apublic method named getPerimeter () that returns the perimeter of the e. f. polygon. Implement this class and write a test program (or, at least, add a main() method) that creates two RegularPolygon objects. The first RegularPolygon should have 5 sides of length 10, while the second RegularPolygon has 12 sides of length 14. Display the properties of both objects and display their perimeter values.Explanation / Answer
class RegularPolygon
{
private int n;
private double side;
public RegularPolygon() //default constructor
{
n = 3;
side = 1;
}
public RegularPolygon(int n,double side) //argument constructor
{
this.n = n;
this.side = side;
}
//get and set functions
public int getN()
{
return n;
}
public double getSide()
{
return side;
}
public void setN(int n)
{
this.n = n;
}
public void setSide(double side)
{
this.side = side;
}
//function to compute perimeter of polygon
public double getPerimeter()
{
return n*side;
}
}
class TestPolygon
{
public static void main (String[] args) throws java.lang.Exception
{
RegularPolygon rp1 = new RegularPolygon(5,10);
RegularPolygon rp2 = new RegularPolygon(12,14);
System.out.println(" The polygon of "+rp1.getN()+" sides with each side of length "+rp1.getSide() + " has perimeter : "+rp1.getPerimeter());
System.out.println(" The polygon of "+rp2.getN()+" sides with each side of length "+rp2.getSide() + " has perimeter : "+rp2.getPerimeter());
}
}
Output:
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.