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.