Help please Java How to program Exercise 84 Rectangle Class
Help please ....... Java How to program Exercise 8.4 (Rectangle Class .Create a class Rectangle with attributes length and width, each of which defaults to 1. Provide methods that calculate the rectangle’s perimeter and area. Use set and get methods for both length and width. The set methods will verify that length and width are each floating-point numbers larger than 0.0 and less than 20.0. Write a program to test class Rectangle
Solution
RectangleTest.java
public class RectangleTest {
public static void main(String[] args) {
Rectangle myRectangle = new Rectangle(4, 15);
System.out.println(\"The area of a rectangle with width \" +
myRectangle.width + \" and height \" +
myRectangle.length + \" is \" +
myRectangle.getArea());
System.out.println(\"The perimeter of a rectangle is \" +
myRectangle.getPerimeter());
Rectangle yourRectangle = new Rectangle(3.5, 15.9);
System.out.println(\"The area of a rectangle with width \" +
yourRectangle.width + \" and height \" +
yourRectangle.length + \" is \" +
yourRectangle.getArea());
System.out.println(\"The perimeter of a rectangle is \" +
yourRectangle.getPerimeter());
}
}
class Rectangle {
public double width =1;
public double length = 1;
public Rectangle(){
}
public Rectangle(double width , double length){
setWidth(width);
setLength( length);
}
public double getArea(){
return width * length;
}
public double getPerimeter(){
return 2 * (width + length);
}
public double getWidth() {
return width;
}
public void setWidth(double width) {
if(width > 0 && width < 20){
this.width = width;
}
}
public double getLength() {
return length;
}
public void setLength(double length) {
if(length > 0 && length < 20){
this.length = length;
}
}
}
Output:
The area of a rectangle with width 4.0 and height 15.0 is 60.0
The perimeter of a rectangle is 38.0
The area of a rectangle with width 3.5 and height 15.9 is 55.65
The perimeter of a rectangle is 38.8

