Answer to Question #321101 in Java | JSP | JSF for Drill

Question #321101

Consider a rectangular shape as an object that has two sides length and width as key attributes, another property is to check if the shape is a square or not. Apart from the ordinary instance methods such as getters, setters and constructors, your class should have the following functionality listed below:

A)   isSquare() : returns true if the values of length and width are equal

B)   calculateArea() : Calculates the area of the shape provide with the respective formula, returning the Area with the formula used

C)   calculatePerimeter(): Calculates the perimeter of the shape returning the result and formula used

D)  Provide a toString() : to represent all the shape attributes and the value returned by the isSquare, including results for the Area and Perimeter as provided above  

1.1.        Provide a simple Class and object diagram for the above scenario                         [30 Marks]


1
Expert's answer
2022-03-30T14:09:59-0400
import java.util.Scanner;

class Rectangle{
    private double length = 1;
    private double width = 1;

    Rectangle(double length, double width){
        setLength(length);
        setWidth(width);
    }

    public void setLength(double length) {
            this.length = length;
    }

    public void setWidth(double width) {
            this.width = width;
    }


    public String CalculateArea(){
        String answ = "Rectangle area = " + (length * width);
        return  answ;
    }


    public String CalculatePerimeter(){
        String answ = "Rectangle perimeter = " + (2 * (length + width));
        return answ;
    }

    public boolean isSquare(){
        if(length == width){
            return true;
        }
        return false;
    }

    @Override
    public String toString() {
        String answ =   "length: " + length + "\n" +
                        "wight: " + width + "\n" +
                        CalculateArea() + "\n" +
                        CalculatePerimeter();
        return answ;
    }
}

public class Main {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        System.out.print("Enter lenght: ");
        double lenght = in.nextDouble();

        System.out.print("Enter wight: ");
        double wight = in.nextDouble();


        Rectangle rec = new Rectangle(lenght, wight);

        System.out.print(rec.toString());
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS