Write a class called Rectangle that does not contain a main() method, but it doe
ID: 653366 • Letter: W
Question
Write a class called Rectangle that does not contain a main() method, but it does contains the following:
Two private double data fields named width and height that specify the width and height of the rectangle.
A no-arg constructor that creates a default rectangle with a value of 1 for the width and 1 for the height.
A two argument constructor that creates a rectangle with the specified width and height.
A public double method named getWidth() that takes no arguments and returns the width of this rectangle.
A public void method named setWidth(double newWidth) that gets one argument and sets the width of the rectangle to the given argument.
A public double method named getHeight() that takes no arguments and returns the height of this rectangle.
A public void method named setHeight(double newHeight) that gets one argument and sets the height of the rectangle to the given argument.
A public double method named getArea() that takes no arguments and returns the area of this rectangle.
A public double method named getPerimeter() that takes no arguments and returns the perimeter of this rectangle.
Next, write a test program called TestRectangle.java that has a main() method, and that creates two Rectangle objects. The first one should have a width of 4 and a height of 40, and the other one should have a width of 3.5 and a heightof 35.9. Then display the width, height, area, and perimeter of each Rectangle in this order.
Explanation / Answer
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class TestRectangle{
public static void main(String[] args) throws IOException
{
BufferedReader reader= new BufferedReader(new InputStreamReader(System.in));
System.out.print("Please enter height of the rectangle : ");
double height = Double.parseDouble(reader.readLine());
setHeight(height);
System.out.print("Please enter width of the rectangle : ");
double width = Double.parseDouble(reader.readLine());
setWidth(width);
System.out.print("Area:"+getArea());
System.out.print("Perimeter:"+getPerimeter());
}
public static double getWidth()
{
int width;
setWidth(width);
return width;
}
public static void setWidth(double newWidth)
{
double width;
newWidth=width;}
public static double getHeight()
{
int height;
setHeight(height);
return height;
}
public static void setHeight(double newHeight)
{
double height;
newHeight=height;
}
public static double getArea()
{
double area= getHeight()*getWidth();
return area;
}
public static double getPerimeter()
{
double perimeter= 2*(getHeight()+getWidth());
return perimeter;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.