-5
 public class Point{

    private double x;
    private double y;
    public Point (double x, double y) {
        this.x = x;
        this.y = y;
    }
    public double getX () {
        return this.x;
    }
    public double getY () {
        return this.y;
    }
    // distance returns the distance between this point and a given point
    public double distance (Point p) {
        return Math.sqrt ((p.x - this.x) * (p.x - this.x) +
                (p.y - this.y) * (p.y - this.y));
    }
    public String toString(){
        return "[" + this.x +","+this.y +"]";
    }

    public static Point nearestPoint(Point[] points, Point point){
        Point p = points[0];
        for(int i = 0; i < points.length; i++){
            if(points[i].distance(point) < p.distance(point)){
                p = points[i];
            }
        }
       return p;
    }

    public static void main(String[] args){
        Point[] points = {new Point(1,2),
                          new Point(2,3),
                          new Point(5,2)};

        Point point = new Point (1,2);
        Point nearestPoint = nearestPoint(points,point);
        System.out.println(nearestPoint);
    }

}

Task 1

A static method, nearestPoint , accepts an array of points (objects of type Point ) and one point (an object of type Point ), and returns that point in the array which is closest to the given point. Create that method.

Task 2

Create an array of points (objects of type Point ) and a point (an object of type Point ). Use the method nearestPoint to determine the point in the array that is closest to the given point.

Question:In Task 1, have I implemented the method nearestPoint correctly as it's asked in the task description? should i declare an array of of object inside that method instead of Point p. This is the output [1.0,2.0] and I'm not sure that this is the correct result?

Any hints , tip suggestion would be great.

1 Answers1

0

Yes. Your implementation seems fine according to your description of nearestPoint method under Task 1. However, you can start your for loop variable i from 1 instead of 0 since you check for distance of the given point from first point in the array in the very first iteration.

    public static Point nearestPoint(Point[] points, Point point) {
    Point p = points[0];
    for (int i = 1; i < points.length; i++) {
        if (points[i].distance(point) < p.distance(point)) {
            p = points[i];
        }
      }
     return p;
   }

Your output is also fine since any point is closest to itself.

qrius
  • 621
  • 2
  • 9
  • 22