Create a class Rectangle. The class has attributes length and width, each of whi
ID: 3531341 • Letter: C
Question
Create a class Rectangle. The class has attributes length and width, each of which defaults to Provide methods that calculate the perimeter and the area of the rectangle. Provide set and get methods for both length and width. The set methods should verify that length and width are each floating-point numbers greater than or equal to 0.0 and less than 20.0. Write a program to test class Rectangle.
Your output should appear as follows:
1. Set Length
2. Set Width
3. Exit
Choice: 1
Enter length: 10
Length: 10.00
Width: 1.00
Perimeter: 22.00
Area: 10.00
1. Set Length
2. Set Width
3. Exit
Choice: 2
Enter width: 15
Length: 10.00
Width: 15.00
Perimeter: 50.00
Area: 150.00
1. Set Length
2. Set Width
3. Exit
Choice: 1
Enter length: 99
Length: 1.00
Width: 15.00
Perimeter: 32.00
Area: 15.00
1. Set Length
2. Set Width
3. Exit
Choice: 3
Explanation / Answer
//RectangleTester.java
import java.util.Scanner;
public class RectangleTester{
public static void main(String[] args) {
Scanner input=new Scanner(System.in);
Rectangle rec=new Rectangle();
double len,wid;
int choice;
do{
System.out.print("1. Set Length 2. Set Width 3. Exit Choice: ");
choice=input.nextInt();
switch(choice){
case 1:
System.out.print("Enter length: ");
len=input.nextDouble();
rec.setLength(len);
System.out.println(rec.toString());
break;
case 2:
System.out.print("Enter width: ");
wid=input.nextDouble();
rec.setLength(wid);
System.out.println(rec.toString());
break;
case 3:
break;
default:
System.out.println("Invalid choice entered.");
}
}while(choice!=3);
input.close();
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Rectangle.java
public class Rectangle {
private double length,width;
public Rectangle(){
length=1;
width=1;
}
public Rectangle(double length,double width){
this.length=length;
this.width=width;
}
//accessor
public void setLength(double length) {
this.length = length;
}
public void setWidth(double width) {
this.width = width;
}
//mutators
public double getLength() {
return length;
}
public double getWidth() {
return width;
}
public double getArea(){
return length*width;
}
public double getPerimeter(){
return 2*(length+width);
}
public String toString(){
String str="";
str+="Length: "+length+" ";
str+="Width: "+width+" ";
str+="Perimeter: "+getPerimeter()+" ";
str+="Area: "+getArea()+" ";
return str;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.