public Segment(Point start, Point end){
if (start == null || end == null)
throw new IllegalArgumentException("引數不能為空")。
if (start.equals(end))
拋出 new IllegalArgumentException("點必須不同") 。
this.start = start;
this.end = end;
}
public Point intersection(Segment another) {
div = dy2 * dx1 - dx2 * dy1;
if (Math.abs(div) < 1.0e-10)
return null。
}
問題是,當我想列印時:
Segment first = new Segment(new Point(0, 0), new Point(0, 0))。)
Segment second = new Segment(new Point(0, 0), new Point(0, 0))。)
Point intersection = first.intersection(second)。
System.out.println(intersection.getX())。
System.out.println(intersection.getY())。
出現NullPointerException的情況,當我引入所有的坐標0。如何解決這個問題?如果有人可以的話,請幫忙。我不明白如何捕捉這個例外或如何解決。
uj5u.com熱心網友回復:
public static Point SegIntersection(double x11, double y11, double x12, double y12,
double x21, double y21, double x22, double y22)
{
double dx1 = x12-x11。
double dy1 = y12-y11;
double dx2 = x22-x21;
double dy2 = y22-y21;
double dxx = x11-x21;
double dyy = y11-y21;
double div, t, s;
div = dy2*dx1-dx2*dy1;
if (Math.abs(div) < 1.0e-10) //最好是用小Eps比較abs(div)。
return null; //collinear case[/span]。
t = (dx1*dyy-dy1*dxx) / div;
if (t < 0 || t > 1.0)
return null; //intersection outside the first segment[/span
s = (dx2*dyy-dy2*dxx) / div;
if (s < 0 || s > 1.0)
return null; //intersection outside the second segment
return new Point(x11 s * dx1, y11 s * dy1)。
注意,該函式不檢查相鄰段的重疊,因為問題陳述忽略了這種情況。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/331096.html
標籤:
