Class Rectangle Create an object that stores information about a rectangle, leng
ID: 3597650 • Letter: C
Question
Explanation / Answer
Rectangle.java
public class Rectangle {
//Declaring instance variables
private double length;
private double width;
//Parameterized constructor
public Rectangle(double length, double width) {
super();
this.length = length;
this.width = width;
}
//This method will increases the length based on argument
public void incLength(double num) {
length = length + num;
}
//This method will increases the width based on argument
public void incWidth(double num) {
width = width + num;
}
//This method will increases the length and width based on argument
public void incLenWidthByPercentage(int percent) {
length += length * ((double) percent / 100);
width += width * ((double) percent / 100);
}
//This method will calculates the area
public double area() {
return length * width;
}
//This method will calculates the perimeter
public double perimeter() {
return 2 * (length + width);
}
//toString method is used to display the contents of an object inside it
@Override
public String toString() {
return "Length=" + length + " Width=" + width + " Area=" + area() + " Perimeter=" + perimeter();
}
}
___________________
Test.java
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
//Declaring variables
int percentage = 0;
String yesOrNo;
/*
* Creating an Scanner class object which is used to get the inputs
* entered by the user
*/
Scanner sc = new Scanner(System.in);
//Creating an Rectangle class instance
Rectangle r = new Rectangle(5, 6);
//Displaying the Rectangle class info
System.out.println(r);
System.out.println("** After Length increases by 2 and width increases by 1 **");
//Increasing the length by 2
r.incLength(2);
//Increasing the length by 1
r.incWidth(1);
//Displaying the Rectangle class info
System.out.println(r);
System.out.print("Do you want to increase the length and width both ?");
yesOrNo = sc.next();
if (yesOrNo.equalsIgnoreCase("yes")) {
System.out.print("By how much percentage :");
percentage = sc.nextInt();
}
r.incLenWidthByPercentage(percentage);
System.out.println(r);
}
}
______________________
Output:
Length=5.0
Width=6.0
Area=30.0
Perimeter=22.0
** After Length increases by 2 and width increases by 1 **
Length=7.0
Width=7.0
Area=49.0
Perimeter=28.0
Do you want to increase the length and width both ?yes
By how much percentage :20
Length=8.4
Width=8.4
Area=70.56
Perimeter=33.6
_____________Could you rate me well.Plz .Thank You