在 Java 中写入 XYRectangle Class

Writing an XYRectangle Class in Java

我有以下class要写: 写一个 class 命名为 XYRectangle_LastName,其中 LastName 替换为您的姓氏。XYRectangle_LastName class 应具有以下字段:

一个名为 TopLeft 的 XYPoint。这存储了矩形左上角的位置。

双重命名长度。这存储了矩形的长度。

双重命名的宽度。这存储了矩形的宽度。

XYRectangle class 应该有以下方法:

随机确定矩形左上角的无参数构造函数。 x 和 y 的值应介于 -10 和 10 之间。此外,它会为矩形选择一个随机宽度和长度,值介于 5 和 10 之间。

一个 3 参数构造函数,它接受左上角的 XYPoint、长度和宽度。

长度、宽度、topLeft、topRight、bottomLeft 和 bottomRight 的获取方法

长度、宽度和左上角的设置方法

名为 isInside 的布尔方法采用 XYPoint 并确定它是否在此矩形内。

一个名为 reflectX 的方法,returns 一个在 x 轴上反射的矩形。

一个名为 reflectY 的方法,returns 一个在 y 轴上反射的矩形。

这是我目前的代码:

public class XYRectangle {

    private XYPoint topLeft;
    private double length;
    private double width;

    public XYRectangle() {
        Random rnd = new Random();
        int x = (rnd.nextInt(21) - 10);
        int y = (rnd.nextInt(21) -10);

        XYPoint topLeft = new XYPoint(x, y);

        int width = (rnd.nextInt(5) + 5);
        int height = (rnd.nextInt(5) + 5);
    }

    public XYRectangle(XYPoint topLeft, double length, double width) {
        this.topLeft = topLeft;
        this.length = length;
        this.width = width;
    }

    public double getLength() { return this.length; }

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

    public double getWidth() { return this.width; }

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

    public XYPoint getTopLeft() { return this.topLeft; }

    public void setTopLeft(XYPoint topLeft) { this.topLeft = topLeft; }

我在使用 topRight、bottomLeft 和 bottomRight get 方法以及 reflect 方法时遇到问题。我什至不确定我到目前为止写的代码是否是写的。任何人都可以帮助并告诉我如何进行以及我是否做错了什么?

你没有关于topRight、bottomLeft、bottomRight的信息,但是有topLeft角和宽度、长度,它完全定义了其他点:

topRight = new XYPoint(topLeft.getX() + length, topLeft.getY());
bottomRight = new XYPoint(topLeft.getX() + length, topLeft.getY() + width);
bottomLeft = new XYPoint(topLeft.getX(), topLeft.getY() + width);

您可以决定在构造对象时存储此信息,或在每次调用 get 方法时计算它。

关于空构造函数,你在应该调用的时候调用了"corner":

public XYRectangle(){
    //code here
}

通常当我们覆盖构造函数时,我们会这样调用基类构造函数:

public XYRectangle(){
    Random rnd = new Random();
    int x = (rnd.nextInt(21) - 10);
    int y = (rnd.nextInt(21) -10);

    XYPoint topLeft = new XYPoint(x, y);

    int width = (rnd.nextInt(5) + 5);
    int height = (rnd.nextInt(5) + 5);
    this(topLeft, width, height)
}

希望大家自己想出反射的方法。 ;)