Point2D等于阈值之内

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

我必须为赋值编写一个Point2D类,到目前为止,我已经能够为除equals()方法之外的所有必要方法编写代码。

我无法确定如何编写代码。 equals方法应该检测表示相同位置的点,在距离阈值内

这里是我到目前为止的代码:

public class Point2D {

    final private double x;
    final private double y;

    /**
     * Constructor to initialize coordinates
     * 
     * @param x x value
     * @param y y value
     */
    public Point2D(double x, double y) {
        this.x = x;
        this.y = y;
    }

    /**
     * Get the x coordinate
     * 
     * @return x coordinate
     */
    public double getX() {
        return x;
    }

    /**
     * Get the y coordinate
     * 
     * @return y coordinate
     */
    public double getY() {
        return y;
    }

    /**
     * Gets a String representation
     * of the coordinate in the form
     * "(x, y)" (each with three decimal
     * places of precision)
     * 
     * @return "(x, y)"
     */
    @Override
    public String toString() {
        return "(" + String.format("%.3f", x) + "," + String.format(" %.3f", y) + ")"; 
    }

    /**
     * Returns true if provided another
     * point that is at the same (x,y)
     * location (that is, the distance
     * is "close enough" according to
     * Shape2D)
     * 
     * @param o another object
     * @return true if the other object is a point and the same location (within threshold)
     */
    @Override
    public boolean equals(Object o) {

    }

    /**
     * Method to compute the Euclidean/L2
     * distance between two points in 2D
     * space
     * 
     * @param p1 point 1
     * @param p2 point 2
     * @return straightline distance between p1 and p2
     */
    public static double distance(Point2D p1, Point2D p2) {
         return Math.sqrt((p2.x - p1.x) * (p2.x - p1.x) + (p2.y - p1.y) * (p2.y - p1.y)); 
    }

    /**
     * Method to compute the Euclidean
     * distance between this point
     * and a supplied point
     * 
     * @param p input point
     * @return straightline distance between this point and p
     */
    public double distanceTo(Point2D p) {
        return Math.sqrt((p.x - x) * (p.x - x) + (p.y - y) * (p.y - y)); 
    }
}
java equals point euclidean-distance
1个回答
0
投票

您可以使用instanceof运算符测试另一个对象的类型,以检查它是否可以强制转换。

Object obj =  // ...
if (obj instanceof Point2D) {
    Point2D otherPoint = (Point2D) obj;
    // Now you can compare otherPoint to this
}
© www.soinside.com 2019 - 2024. All rights reserved.