Create a class called Rectangle with two instance variables width and height tha
ID: 3601250 • Letter: C
Question
Create a class called Rectangle with two instance variables width and height that are of type double. Provide a method called calculatePerimeter that calculates the perimeter of the rectangle, and provide a method called calculateArea that calculates the area of the rectangle. Both methods should return doubles. The class should also have set and get methods for setting and getting the width and height instance variables. The set methods should verify that the length and width specified should be within the range of 0.0 and 20.0. Ensure you code is commented well, especially the set methods explaining the input restrictions and what happens if the restrictions are not met.
Write a program to test the Rectangle class.
Explanation / Answer
//Please see the below code and output
import java.util.Scanner;
public class Rectangle
{
private static double height;
private static double width;
public Rectangle() {
height =0.0;
width=0.0;
}
public Rectangle(double h, double w) {
if(w>=0.0 && w<= 20.0 && h>=0.0 && h<=20.0)
{
height = h;
width = w;
}
else
{
System.out.println("height and Width is not in range 0.0 and 20.0");
}
}
public double calculateArea () {
return height *width;
}
public double calculatePerimeter() {
return height *2 + width*2;
}
public void setwidth(double w)
{
if(w>=0.0 && w<= 20.0)
width=w;
else
System.out.println("Error: Width is not in range 0.0 and 20.0");
}
public double getwidth()
{
return width;
}
public void setHeight(double h)
{
if(h>=0.0 && h<= 20.0)
height=h;
else
System.out.println("Error: height is not in range 0.0 and 20.0");
}
public double getHeight()
{
return height;
}
public static void main(String[] args)
{
Rectangle rect = new Rectangle();
rect.setHeight(10);
rect.setwidth(10);
System.out.println("Area of the Rectangle is "+rect.calculateArea());
System.out.println("Perimeter of the Retangle is "+ rect.calculatePerimeter());
}
}
OUTPUT:
Area of the Rectangle is 100.0
Perimeter of the Retangle is 40.0
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.