Java Reference
In-Depth Information
// Return a point as the intersection of two lines
Point intersects(final Line line1) {
Point localPoint = new Point(0, 0);
double num = (end.y - start.y)*(start.x - line1.start.x) -
(end.x - start.x)*(start.y - line1.start.y);
double denom = (end.y - start.y)*(line1.end.x - line1.start.x) -
(end.x - start.x)*(line1.end.y - line1.start.y);
localPoint.x = line1.start.x + (line1.end.x - line1.start.x)*num/
denom;
localPoint.y = line1.start.y + (line1.end.y - line1.start.y)*num/
denom;
return localPoint;
}
Directory "Try Geometry"
Because the
Line
class definition refers to the
Point
class, the
Line
class can't be compiled without the
other being available. When you compile the
Line
class, the compiler compiles the other class, too.
How It Works
The
intersects()
method is called for one
Line
object and takes another
Line
object as the argument.
In the code, the local variables
num
and
denom
are the numerator and denominator in the expression for
t
in
Figure 5-8
.
You then use these values to calculate the
x
and
y
coordinates for the intersection point.
WARNING
If the lines are parallel, the denominator in the equation for
t
is zero,
somethingyoushouldreallycheckforinthecode.Forthemomentyouignoreitand
end up with coordinates that are
Infinity
if it occurs.
Note how you get at the values of the coordinates for the
Point
objects defining the lines. The dot nota-
tion for referring to a member of an object is just repeated when you want to reference a member of a
member. For example, for the object
line1
, the expression
line1.start
refers to the
Point
object at the
beginning of the line. Therefore,
line1.start.x
refers to its
x
coordinate, and
line1.start.y
accesses
its
y
coordinate.
Now you have a
Line
class defined that you can use to calculate the intersection point of two
Line
ob-
jects. You need a program to test the code out.