我希望写一个带有 Point 和 Line 的构造函数的类,并且在Line类中我希望写一个查找两条线是否相交的方法。这是我的Point类:
public class Point {
static double x;
static double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
}
这是我的Line Class
public class Line {
public Line(Point x, Point y) {
}
// create two points for a line
static Point x1y1;
static Point x2y2;
// create another two points for another line
static Point x3y3;
static Point x4y4;
public static void main(String[] args) {
// create lines
Line line1 = new Line(x1y1, x2y2);
Line line2 = new Line(x3y3, x4y4);
//initialize points
x1y1 = new Point(1.0, 1.0);
x2y2 = new Point(3.0, 3.0);
x3y3 = new Point(1.0, 2.0);
x4y4 = new Point(4.0, 2.0);
//call method to find if lines intersect
findIntersection(line1, line2);
System.out.println(x1y1.x);
}
public static void findIntersection(Line line1, Line line2) {
double denominator = (x1y1.x - x2y2.x) * (x3y3.y - x4y4.y)
- (x1y1.y - x2y2.y) * (x3y3.x - x4y4.x);
double px = 0;
double py = 0;
if (denominator == 0) {
System.out.println("Lines are parallel, they do not intersect");
} else {
px = ((x1y1.x * x2y2.y - x1y1.y * x2y2.x) * (x3y3.x - x4y4.x) - (x1y1.x - x2y2.x)
* (x3y3.x * x4y4.y - x3y3.y * x4y4.x))
/ denominator;
py = ((x1y1.x * x2y2.y - x1y1.y * x2y2.x) * (x3y3.y - x4y4.y) - (x1y1.y - x2y2.y)
* (x3y3.x * x4y4.y - x3y3.y * x4y4.x))
/ denominator;
System.out.println(px + "," + py);
}
}
}
问题是我初始化所有点以使线条相交,但是当我尝试打印出点的值时,第1点的x-es和ys的值等于第4点一个虽然我用不同的值初始化它们,因此该方法计算出线不相交。为什么前三个y和x的值等于第四个?
答案 0 :(得分:0)
这是因为x
类的y
和Point
是static
。这意味着,Point
类的每个实例都将使用相同的值。删除static
以修复它。
public class Point {
double x;
double y;
你应该改进课程设计:两个类(Point,Lines)另一个用main方法。
Line也一样。或者你最终会得到每一行相同的积分。 (你想用4个变量来避免这种情况。)
像这样的东西
public class Point {
double x;
double y;
public Point(double x, double y) {
this.x = x;
this.y = y;
}
}
public class Line {
Point a;
Point b;
public Line(Point a, Point b) {
this.a = a;
this.b = b;
}
public Point itIntersect(Line line) {
// here change the logic
Point point = null;
double denominator = (x1y1.x - x2y2.x) * (x3y3.y - x4y4.y)
- (x1y1.y - x2y2.y) * (x3y3.x - x4y4.x);
double px = 0;
double py = 0;
if (denominator != 0) {
px = ((x1y1.x * x2y2.y - x1y1.y * x2y2.x) * (x3y3.x - x4y4.x) - (x1y1.x - x2y2.x)
* (x3y3.x * x4y4.y - x3y3.y * x4y4.x))
/ denominator;
py = ((x1y1.x * x2y2.y - x1y1.y * x2y2.x) * (x3y3.y - x4y4.y) - (x1y1.y - x2y2.y)
* (x3y3.x * x4y4.y - x3y3.y * x4y4.x))
/ denominator;
// System.out.println(px + "," + py);
point = new Point(px, py);
}
return point;
}
}
P.S我没有改变交叉的逻辑,因为它太长了,但你可以做这样的事情来改进设计。
然后你需要做Point point = line.itIntersect(anotherLine);
如果它为null则不相交,否则它将返回该点。
P.S将x
和y
设为私有,我没有,因为它是一个例子。