【问题标题】:Java While loop never endsJava While 循环永远不会结束
【发布时间】: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) &amp;&amp; (yPosition != yTarget的值。这是您在while 循环中的状况的问题。
  • 尝试检查它是否与target接近,而不是完全相同。 double 类型可能非常长,即使 0.00001 关闭也会被视为不相等。
  • xPosition 和 yPosition 是双精度的,在两个函数之外声明,不是静态的只是双精度

标签: java while-loop


【解决方案1】:

你有一个逻辑错误:

你说:“如果 destination.X 比 source.X 的 '1' 更近,那么不要再靠近 (dx = 0)。”

这可能会永远持续下去。

回答您的评论问题(评论部分空间不足和编辑):

if (Math.abs(dest.coords.getX() - source.coords.getX()) &lt; 1)if (Math.abs(dest.coords.getY() - source.coords.getY()) &lt; 1) 移出到while 循环的条件中。

您不想在 update() 方法内接近时停止更改位置,而是希望您的循环停止。否则循环将继续运行,update() 方法将什么也不做。

【讨论】:

  • 像这样:while( (Math.abs(dest.coords.getX() - source.coords.getX())
  • 这样移动?或者..?
【解决方案2】:

使用==!= 比较double 变量肯定会给您带来麻烦,因为最小的舍入错误会破坏您的比较。使用 Math.abs(xPosition - xTarget) &lt; tolerance 之类的东西。

【讨论】: