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

Java How To Program (Early Objects)(10th Edition) Chapter 8 Exercise 8.4 : Creat

ID: 3602037 • Letter: J

Question

Java How To Program (Early Objects)(10th Edition) Chapter 8

Exercise 8.4: 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.

Important note: Please add brief comments to most, if not all of the code to explain what is being done in the code so I have a better understanding of what's being used in the code and what it's doing. Also, could you make sure the user is propmpted for the length and the width? Thank you.

Explanation / Answer

package classesObjects;

public class Rectangle {

// set the attributes of length and width to 1 (default)
float length=1;
float width=1;

public float getLength() {
return length;
}

// check the validity of length
private float setLength(float length) {
if ((length>0.0)&&(length<20.0))
{
return length;
}
else
{
System.out.printf("Invalid length (%.2f) set to 1.n",length);
return 1;
} // end if-else
} // end setLength(float length) method

public float getWidth() {
return width;
}

// check the validity of width
private float setWidth(float width) {
if ((width>0.0)&&(width<20.0))
{
return width;
}
else
{
System.out.printf("Invalid width (%.2f) set to 1.n",width);
return 1;
} // end if-else
} // end setWidth(float width) method

// calculates the perimeter after validates the length and width
public float calcPerimeter(float length, float width)
{
float perimeter=2 * (length + width);
return perimeter;
} // end calcPerimeter

// calculates the area after validates the length and width
public float calcArea(float length, float width)
{
float area= length * width;
return area;
} // end calcArea

public static void main(String[] args) {
// TODO Auto-generated method stub

Rectangle r=new Rectangle();
// Test 1 - Valid length and width
System.out.println("*** Test 1 - Valid length and width ***");
float l=r.setLength(5);
float w=r.setWidth(2);
float a=r.calcArea(l, w);
float p=r.calcPerimeter(l, w);
System.out.println("Area: "+a+"nPerimeter: "+p);

System.out.println();
// Test 2 - Invalid length and width
System.out.println("*** Test 2 - Invalid length and width ***");
float l2=r.setLength(21);
float w2=r.setWidth(-1);
float a2=r.calcArea(l2, w2);
float p2=r.calcPerimeter(l2, w2);
System.out.println("Area: "+a2+"nPerimeter: "+p2);

} // end main()
} // end Rectangle class

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote