公共 Point2D 中点()

问题描述 投票:0回答:1

顺便说一下,java 代码,其中包括 来自 2 个不同类的代码

  • 公共 Point2D 中点(Point2D 其他)

    此方法创建并返回一个新的、不同的 Point2D 对象,该对象是由该 Point2D 对象和 other 引用的 Point2D 对象形成的线段的中点。例如,点 (1, 2) 和 (3, 4) 的中点是新点 (2, 3)。该方法假设中点的 x 和 y 坐标都是整数。

    来自 Point2D 类

  • public Point2D 中点()

    此方法返回作为此 Line2D 对象的中点的 Point2D 对象。该方法必须调用 Point2D 中的中点方法来获取该对象的实例变量,利用那里实现的操作。

    来自line2D类

这是我尝试的代码Point2D 类

public Point2D midpoint(Point2D other) {
        this.x = x + other.x;
        this.y = y + other.y;
        return new Point2D(x / 2, y / 2);

这是我为 line2D 类尝试的代码:

public Point2D midpoint() {
        return new Point2D((endPoint1.getX() + endPoint2.getX()) / 2, (endPoint1.getY() + endPoint2.getY()) / 2);

但我没有得到我预期的结果

java computer-science
1个回答
0
投票

您可以在

midpoint()
方法中修改 this 对象。它可能会导致意外的行为。相反,您应该创建一个新的 Point2D 对象来表示中点。

此外,您也不要在

midpoint()
方法中使用
class Point2D
中的
midpoint()
方法。相反,您自己计算
midpoint
。这是不必要的,因为
class Point2D
已经提供了
midpoint()
方法。

更新代码:

public Point2D midpoint(Point2D other) {
  return new Point2D((this.x + other.x) / 2, (this.y + other.y) / 2);
}

public Point2D midpoint() {
  return endPoint1.midpoint(endPoint2);
}
© www.soinside.com 2019 - 2024. All rights reserved.