Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Extend the class named Rectangle which you created in the previous assignment. T

ID: 3711639 • Letter: E

Question

Extend the class named Rectangle which you created in the previous assignment. The class needs to contain all of the previous constructors and methods plus the following items:

A method named setWidth() that sets the width of a rectangle object to a specified width. If the specified width is less than or equal to zero, then it sets the width to one.

A method named setHeight() that sets the height of a rectangle object to a specified height. If the specified height is less than or equal to zero, then it sets the height to one.

Modify your rectangle constructor which includes parameters for width and height to use the setWidth() and setHeight()methods. This will validate the input for both width and height.

Modify the BuildRectangles class to create three separate rectangles with the following specifications:

A rectangle created using the no-arg constructor

A rectangle with a width of -5 and a height of 0

A rectangle with a width of 3.5 and a height of 66.1

Output the information about the three rectangles as you did in the previous assignment:

Explanation / Answer

BuildRectangles.java


public class BuildRectangles {

public static void main(String []args){
Rectangle r1 = new Rectangle();
System.out.println("Width: "+r1.getWidth()+" Height: "+r1.getHeight());
Rectangle r2 = new Rectangle(-5, 0);
System.out.println("Width: "+r2.getWidth()+" Height: "+r2.getHeight());
Rectangle r3 = new Rectangle(3.5, 66.1);
System.out.println("Width: "+r3.getWidth()+" Height: "+r3.getHeight());
}
}

Rectangle.java

public


class Rectangle {
private double width, height;
public Rectangle() {
this.width = 1;
this.height = 1;
}
public Rectangle(double width, double height) {
setWidth(width);
setHeight(height);
}
public void setWidth(double width) {
if(width <= 0) {
this.width = 1;
} else {
this.width = width;
}
}
public void setHeight(double height) {
if(height <= 0) {
this.height = 1;
} else {
this.height = height;
}
}
public double getWidth() {
return width;
}
public double getHeight() {
return height;
}

}

Output:

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Chat Now And Get Quote