题目
(几何:交点)假设两条线段相交。第一条线段的两个端点是(x1, y1)和(x2, y2),第二条线段的两个端点是(x3, y3)和(x4, y4)。编写一个程序,提示用户输入这四个端点,然后显示它们的交点。如编程练习题3.25所讨论的,可以通过对一个线性方程求解来得到。使用编程练习题9.11中的LinearEquation类来求解该方程。参见编程练习题3.25的运行示例。
(Geometry: Intersection) Assuming that two line segments intersect. The two endpoints of the first line segment are (x1, y1) and (x2, y2), while the two endpoints of the second line segment are (x3, y3) and (x4, y4). Write a program that prompts the user to enter these four endpoints and displays their intersection points. As discussed in programming exercise 3.25, it can be obtained by solving a linear equation. Use the LinearEquation class from programming exercise 9.11 to solve the equation. Refer to the running example in programming exercise question 3.25.
代码
Test.java
public class Test {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Enter four endpoints for two lines: x1, y1, x2, y2, x3, y3, x4, y4: ");
double[] nums = new double[8];
for (int i = 0; i < 8; i++) {
nums[i] = in.nextDouble();
}
double a = nums[1] - nums[3];
double b = -(nums[0] - nums[2]);
double c = nums[5] - nums[7];
double d = -(nums[4] - nums[6]);
double e = (nums[1] - nums[3]) * nums[0] - (nums[0] - nums[2]) * nums[1];
double f = (nums[5] - nums[7]) * nums[4] - (nums[4] - nums[6]) * nums[5];
LinearEquation linearEquation = new LinearEquation(a, b, c, d, e, f);
if (linearEquation.isSolvable()) {
System.out.printf("The intersecting point is at (%.2f, %.2f)", linearEquation.getX(),
linearEquation.getY());
} else {
System.out.println("The equation does not have a solution with the points provided.");
}
}
}
LinearEquation.java
class LinearEquation {
private double a;
private double b;
private double c;
private double d;
private double e;
private double f;
LinearEquation(double a, double b, double c, double d, double e, double f) {
this.a = a;
this.b = b;
this.c = c;
this.d = d;
this.e = e;
this.f = f;
}
double getA() {
return a;
}
double getB() {
return b;
}
double getC() {
return c;
}
double getD() {
return d;
}
double getE() {
return e;
}
double getF() {
return f;
}
boolean isSolvable() {
if (a * d - b * c != 0) {
return true;
}
return false;
}
double getX() {
return (e * d - b * f) / (a * d - b * c);
}
double getY() {
return (a * f - e * c) / (a * d - b * c);
}
}
结果