一、核心代码理解

boolean result = false;
int i = 0;
for (int j = this.points.length - 1; i < this.points.length; j = i++) {
if (this.points[i].y > test.y != this.points[j].y > test.y
&& test.x < (this.points[j].x - this.points[i].x)
* (test.y - this.points[i].y) / (this.points[j].y - this.points[i].y) + this.points[i].x)
{
result = !result;
}
}
return result;
二、代码如下
public class TTest70 {
public static void main(String[] args) {
BoundaryPoint boundaryPoint = new BoundaryPoint(1, 1);
BoundaryPoint boundaryPoint1 = new BoundaryPoint(9, 9);
BoundaryPoint boundaryPoint2 = new BoundaryPoint(4, 0.5);
BoundaryPoint[] boundaryPoints = new BoundaryPoint[]{boundaryPoint,boundaryPoint1,boundaryPoint2};
Boundary boundary = new Boundary(boundaryPoints);
BoundaryPoint boundaryPoint4 = new BoundaryPoint(6, 1);
boolean contains = boundary.contains(boundaryPoint4);
System.out.println(contains);
}
static class BoundaryPoint {
public final double x;
public final double y;
public BoundaryPoint(double x, double y) {
this.x = x;
this.y = y;
}
}
static class Boundary {
private final BoundaryPoint[] points;
Boundary(BoundaryPoint[] points) {
this.points = points;
}
boolean contains(BoundaryPoint test) {
boolean result = false;
int i = 0;
for (int j = this.points.length - 1; i < this.points.length; j = i++) {
if (this.points[i].y > test.y != this.points[j].y > test.y
&& test.x < (this.points[j].x - this.points[i].x) * (test.y - this.points[i].y) / (this.points[j].y - this.points[i].y) + this.points[i].x) {
result = !result;
}
}
return result;
}
}
}