gpt4 book ai didi

Java While 循环永远不会结束

转载 作者:行者123 更新时间:2023-12-01 07:27:49 25 4
gpt4 key购买 nike

我的 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;
}
}

最佳答案

你有一个逻辑错误:

你说:“如果destination.X距离source.X比'1'更近,那么就不要将其移得更近(dx = 0)。”

这种情况可能会永远持续下去。

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

移动if (Math.abs(dest.coords.getX() - source.coords.getX()) < 1)if (Math.abs(dest.coords.getY() - source.coords.getY()) < 1) out 进入 while 循环的条件。

当位置接近 update() 方法时,您不想停止更改位置,而是希望循环停止。否则循环将继续运行并且 update() 方法将不执行任何操作。

关于Java While 循环永远不会结束,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21377780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com