Saturday, June 21, 2014

Java Exercise Nr. 39 (Selections)

Two points on line 1 are given as (x1 , y1) and (x2 ,y2) and on line 2 as (x3 , y3) and (x4 , y4), as shown in figure a–b. The intersecting point of the two lines can be found by solving the following linear equation:
This linear equation can be solved using Cramer’s rule. If the equation has no solutions, the two lines are parallel (figure c).Write a program that prompts the user to enter four points and displays the intersecting point.

Solution:

Cramer's Rule




public static void main(String[] args) {
Scanner s = new Scanner(System.in);
double x1, y1, x2, y2, x3, y3, x4, y4;
double a, b, c, d, e, f;
double x, y;

System.out.print("Enter x1, y1, x2, y2, x3, y3, x4, y4:");
x1 = s.nextDouble();
y1 = s.nextDouble();
x2 = s.nextDouble();
y2 = s.nextDouble();
x3 = s.nextDouble();
y3 = s.nextDouble();
x4 = s.nextDouble();
y4 = s.nextDouble();

a = y1 - y2;
b = x1 - x2;
e = (y1 - y2) * x1 - (x1 - x2) * y1;
c = y3 - y4;
d = x3 - x4;
f = (y3 - y4) * x3 - (x3 - x4) * y3;

if(a*d - b*c == 0) {
System.out.print("The two lines are parallel.");
} else {
x = (e*d - b*f)/(a*d - b*c);
y = (a*f - e*c)/(a*d - b*c);

System.out.print("The intersecting point is at (" + x + ", " + y + ").");
}
}

No comments:

Post a Comment

Author