The problem Two points on line 1 are given as (x1, y1) and (x2, y2) and on line 2 as (x3, y3) and (x4, y4)
The intersecting point of the two lines can be found by solving the following lin- ear equation:
(y1 -y2)x-(x1 -x2)y=(y1 -y2)x1 -(x1 -x2)y1 (y3 -y4)x-(x3 -x4)y=(y3 -y4)x3 -(x3 -x4)y3
This linear equation can be solved using Cramer’s rule. If the equation has no solutions, the two lines are parallel. Write a program that prompts the user to enter four points and displays the intersecting point. Here are sample program :
Enter x1, y1, x2, y2, x3, y3, x4, y4: 2 2 5 -1.0 4.0 2.0 -1.0 -2.0 The intersecting point is at (2.88889, 1.1111)
Breaking it down public static void main ( String [] strings ) {
Scanner input = new Scanner ( System . in );
System . out . print ( "Enter x1, y1, x2, y2, x3, y3, x4, y4: " );
double x1 = input . nextDouble ();
double y1 = input . nextDouble ();
double x2 = input . nextDouble ();
double y2 = input . nextDouble ();
double x3 = input . nextDouble ();
double y3 = input . nextDouble ();
double x4 = input . nextDouble ();
double y4 = input . nextDouble ();
input . close ();
double a = y1 - y2 ;
double b = -( x1 - x2 );
double c = y3 - y4 ;
double d = -( x3 - x4 );
double e = ( y1 - y2 ) * x1 - ( x1 - x2 ) * y1 ;
double f = ( y3 - y4 ) * x3 - ( x3 - x4 ) * y3 ;
double abMinusBC = a * d - b * c ;
double x = ( e * d - b * f ) / abMinusBC ;
double y = ( a * f - e * c ) / abMinusBC ;
if ( abMinusBC == 0 ) {
System . out . println ( "The two lines are parallel" );
} else {
System . out . println ( "The intersecting point is at (" + x + ", " + y
+ ")" );
}
}
Output Enter x1, y1, x2, y2, x3, y3, x4, y4: 2 2 5 -1.0 4.0 2.0 -1.0 -2.0
The intersecting point is at (2.888888888888889, 1.1111111111111112)
Geometry intersecting point posted by Justin Musgrove on 08 April 2016
Tagged: java, java-exercises-beginner, intro-to-java-10th-edition, and ch3
Share on: Facebook Google+