Answer to Question #287186 in Java | JSP | JSF for HEHE

Question #287186

Rectangles in a Cartesian plane are represented by a class Rectangle that has four private fields as shown:

class Rectangle{

private int left

private int bottom

private int width

private int height

e.Write a class method, intersection, that has two Rectangle parameters. The method should return the rectangle formed by the area common to the two rectangles. If they do not intersect, the method should return the rectangle whose instance fields are all zero. If the rectangles touch, the method should return a "rectangle" of zero width or zero length.


Please answer whole question which is question 8 on http://ntci.on.ca/compsci/java/ch6/6_10.html





1
Expert's answer
2022-01-13T08:37:00-0500
public class Rectangle {
    private int left;
    private int bottom;
    private int width;
    private int height;

    public Rectangle(int left, int bottom, int width, int height) {
        this.left = left > 0 ? left : 0;
        this.bottom = bottom > 0 ? bottom : 0;
        this.width = width > 0 ? width : 0;
        this.height = height > 0 ? height : 0;
    }

    public String toString() {
        return "base:(" + left + "," + bottom + ") w:" + width + " h:" + height;
    }

    public int area() {
        return width * height;
    }

    public int perimeter() {
        return 2 * (width + height);
    }

    public static Rectangle intersection(Rectangle a, Rectangle b) {
        int xALeft = a.left;
        int xARight = a.left + a.width;
        int yATop = a.bottom + a.height;
        int yABottom = a.bottom;

        int xBLeft = b.left;
        int xBRight = b.left + b.width;
        int yBTop = b.bottom + b.height;
        int yBBottom = b.bottom;

        if (xBLeft > xARight || xALeft > xBRight || yABottom > yBTop || yBBottom > yATop) {
            return new Rectangle(0, 0, 0, 0);
        } else {
            int left = Math.max(xALeft, xBLeft);
            int right = Math.min(xARight, xBRight);
            int bottom = Math.max(yABottom, yBBottom);
            int top = Math.min(yATop, yBTop);
            return new Rectangle(left, bottom, right - left, top - bottom);
        }
    }

    public static int totalPerimeter(Rectangle a, Rectangle b) {
        return a.perimeter() + b.perimeter() - intersection(a, b).perimeter();
    }

    public boolean contains(Rectangle rectangle) {
        return left <= rectangle.left && left + width >= rectangle.left + rectangle.width &&
                bottom <= rectangle.bottom && bottom + height >= rectangle.bottom + rectangle.height;
    }
}

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