Point2D равен в пределах порога - PullRequest
0 голосов
/ 29 марта 2020

Мне нужно написать класс 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)); 
    }
}

1 Ответ

0 голосов
/ 29 марта 2020

Вы можете использовать оператор instanceof, чтобы проверить тип другого объекта и проверить, можно ли его привести.

Object obj =  // ...
if (obj instanceof Point2D) {
    Point2D otherPoint = (Point2D) obj;
    // Now you can compare otherPoint to this
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...