【发布时间】:2025-12-24 13:55:11
【问题描述】:
我有一个 while 循环的问题。看起来它永远不会结束,并且 tryLadowanie() 永远不会运行。我想这有什么问题:while( (xPosition != xTarget) && (yPosition != yTarget) )。 Update() 工作得很好,它从 A 点到 B 点就好了,但是一旦它在 B 点它仍然运行。你怎么看?
这是我的代码:
public void lecimy(Lotnisko source, Lotnisko dest){
xPosition = source.coords.getX();
yPosition = source.coords.getY();
xTarget = dest.coords.getX();
yTarget = dest.coords.getY();
while( (xPosition != xTarget) && (yPosition != yTarget) ) {
update();
try {
sleep(100);// ok
}
catch (InterruptedException e) {
System.out.println("Error");
}
}
tryLadowanie();
}
public void update() {
paliwo -= 0.05;
double dx = xTarget - xPosition;
double dy = yTarget - yPosition;
double length = sqrt(dx*dx+dy*dy);
dx /= length;
dy /= length;
if (Math.abs(dest.coords.getX() - source.coords.getX()) < 1)
dx = 0;
if (Math.abs(dest.coords.getY() - source.coords.getY()) < 1)
dy = 0;
xPosition += dx;
yPosition += dy;
}
}
【问题讨论】:
-
您在哪里声明了 xPosition 和 yPosition?在两个函数之外的某个地方声明?静态的?
-
打印和调试
xPosition != xTarget) && (yPosition != yTarget的值。这是您在while循环中的状况的问题。 -
尝试检查它是否与
target接近,而不是完全相同。double类型可能非常长,即使0.00001关闭也会被视为不相等。 -
xPosition 和 yPosition 是双精度的,在两个函数之外声明,不是静态的只是双精度
标签: java while-loop