I am wondering how you would write a java method finding the closest Double to a given list of Segments. I can't figure out how to move on...Any suggestion or code demonstration will be very helpful.
For example: Let's say I have a line segment -> [x1,x2]. What I need is to return X if it lies on this line segment. Otherwise, return x1 or x2 if the given value, in this case "X" is the nearest value to x1 or to x2. Example: [2.1, 4.2]. x=1. The result should be 2.1 because is closer to 1. Thanks in advance. Here is my code:
public class LineSegment {
private Point p1;
private Point p2;
public Point getP1() {
return p1;
}
public Point getP2() {
return p2;
}
public LineSegment(Point p1, Point p2) {
this.p1 = p1;
this.p2 = p2;
}
// Find X or the closest value to X
private Double findNearestX(Double x, List<LineSegment> lSeg) {
Double max = Double.MAX_VALUE;
double closest;
// Get X in case it's inside the list
for (LineSegment ls : lSeg)
if (lSeg.contains(x))
return x;
// otherwise...what to do next!
return null;
}
}