java - 有没有办法在没有静态变量 JAVA 的情况下将数据从一个函数“传输”到另一个函数?
问题描述
下面的代码有 2 个函数。(感谢帮助我的@AlexRudenko)
他们都得到一个段,一条线(不一定是不定式)。除了他们已经拥有的那个。第一个函数检查是否有一个交点(只有一个),并返回一个布尔值。第二个应该检查相同并返回点本身。
// Returns true if the lines intersect, false otherwise
public boolean isIntersecting(Line other) {
if (equals(other)){
return false;
}
double x11 = this.start.getX();
double y11 = this.start.getY();
double x12 = this.end.getX();
double y12 = this.end.getY();
double x21 = other.start.getX();
double y21 = other.start.getY();
double x22 = other.end.getX();
double y22 = other.end.getY();
if (x11 == x12 && x21 == x22) { // both lines are constant x
// no intersection point
return false;
} else if (x11 == x12 || x21 == x22) { // either line is constant x
double x;
double m;
double b;
if (x11 == x12) { // first line is constant x, second is sloped
x = x11;
m = (y22 - y21) / (x22 - x21);
b = (x22 * y21 - x21 * y22) / (x22 - x21);
} else { // second line is constant x, first is sloped
x = x21;
m = (y12 - y11) / (x12 - x11);
b = (x12 * y11 - x11 * y12) / (x12 - x11);
}
double y = m * x + b;
Point.intersection = new Point (x,y);
return true;
} else { // both lines are sloped
double m1 = (y12 - y11) / (x12 - x11);
double b1 = (x12 * y11 - x11 * y12) / (x12 - x11);
double m2 = (y22 - y21) / (x22 - x21);
double b2 = (x22 * y21 - x21 * y22) / (x22 - x21);
if ((long) m1 == (long) m2) {
// no intersection point
return false;
}
// calculating intersection coordinates
double x = (b2 - b1)/(m1 - m2);
double y = m1 * x + b1; // or m2 * x + b2
Point.intersection = new Point (x,y);
return true;
}
}
// Returns the intersection point if the lines intersect,
// and null otherwise.
public Point intersectionWith(Line other) {
if (isIntersecting(other)) {
return Point.intersection;
}
return null;
}
在返回“true”值之前,我考虑过在第一个函数中“保存”静态变量中的点,然后使用这个静态变量“拉”第二个函数中的点并返回它的值。
另外,你认为关于段而不是不定式,我应该在第一个函数中添加更多条件吗?我的意思是是的,可以说两者具有相同的斜率,但这并不意味着它们不能只有一个交点。因为如果我们在谈论 Line1: (1,0) (1,2) 和 Line2: (1,2) (1,3) 它们都有相同的斜率,但它们仍然在 (1,2) 处有一个交点)。那么你认为我应该在代码中添加什么来消除所有这些情况?我想到了类似的东西:
if(!this.start().equals(line.start())
||!this.start().equals(line.end())
||!this.end().equals(line.start())
||!this.end().equals(line.end()))
return false;
我想我还应该添加一个小检查来检查交叉点是否在两个段上。我应该取交点的 X 和 Y 值并检查 X 值是否在起点的 X 值和终点的 X 值之间(在两个段上)并对 Y 值进行相同的检查。你怎么看?
谢谢。
解决方案
反过来说不是更容易吗?
public Point isIntersecting(Line other) {
//your calculation here
return Point
}
public Boolean intersectionWith(Line other) {
Point p=isIntersecting(other)
if(p==null)
return false
return true
}
推荐阅读
- javascript - 将两个javascript函数合二为一
- python - 如何安装与 pip v20.3 版本不兼容的软件包?
- powershell - Powershell:强制或强制转换为字符串变量中命名的类型
- view - Bootstrap 模态窗口和 Thymeleaf
- numpy - 向 NP 数组添加新维度
- java - 使用捆绑的库 Websphere 自由
- javascript - 到达特定日期时如何自动更改 MongoDB 中的属性值
- php - 如何在 Mac OS Big Sur 中更改 xampp htdocs 目录
- javascript - 如何在另一个函数中传递函数返回的值
- html - CSS 中的响应式工具提示