gpt4 book ai didi

java - java中多个条件的while循环

转载 作者:行者123 更新时间:2023-12-02 06:55:23 25 4
gpt4 key购买 nike

这里是 Java 新手。我有多个 while 循环。所有分离的人都认为它会按顺序下降,直到 while 条件等于 true。我的输出表明它执行第一个 while 循环,它发现该循环为 true,然后退出,而不查看其他循环。如果有更好的方法或者您看到明显的错误,请告知。 (xCar =3, yCar =3) 和 Destination = (1,1) 的示例输出只是“West”“West”。应该有2个“南”。 *请原谅打印语句,我正在尝试调试它正在做什么。我还应该指出,我只能将“汽车”移动一个位置,然后需要报告方向。

if (car.getLocation().equals(car.getDestination())){

System.out.println("inside this if statement");
System.out.println(car.nextMove().NOWHERE);
}


//Seeing if Xcar is greater than Xdest. If so moving west
while (car.getxCar() > xDestination){
System.out.println("2nd if statement");
System.out.println(car.nextMove().WEST);
}
//Seeing if Xcar is less than Xdest. If so moving east
while (car.getxCar() < xDestination){
//System.out.println("3rd");
System.out.println(car.nextMove().EAST);

}
//Seeing if Ycar is greater than Ydest. If so moving south
while (car.getyCar() > yDestination){
System.out.println("4th");
System.out.println(car.nextMove().SOUTH);
}
//Seeing if Ycar is less than Ydest. If so moving north
while (car.getyCar() < yDestination){
System.out.println("5th");
System.out.println(car.nextMove().NORTH);
}

METHOD nextMove() 它正在调用 Direction 类中的枚举

public Direction nextMove() {
if (xCar < xDestination){
xCar = xCar + car.x+ 1;
}
if (xCar > xDestination){
xCar = xCar + car.x -1;
}
if (yCar < yDestination){
yCar = yCar + car.y +1;
}
if (yCar > yDestination){
yCar = yCar + car.y -1;
}
return null;

输出

 Car [id = car17, location = [x=3, y=3], destination = [x=1, y=1]]
2nd if statement
WEST
2nd if statement
WEST

最佳答案

发生的事情是这样的:

在第一个 while 循环中,您调用 nextMove() 方法。此方法在第一个循环中同时递增 x 和 y,因此您无法获得其他 while 循环的输出。如果您将输入目的地更改为 [3,4],您应该得到 WEST,WEST,SOUTH 的输出

您可以修复此问题,以便在 nextMove() 方法中一次仅增加一个维度,方法是将它们更改为 else if,如下所示

public Direction nextMove() {
if (xCar < xDestination){
xCar = xCar + car.x+ 1;
}
else if (xCar > xDestination){
xCar = xCar + car.x -1;
}
else if (yCar < yDestination){
yCar = yCar + car.y +1;
}
else if (yCar > yDestination){
yCar = yCar + car.y -1;
}
return null;

关于java - java中多个条件的while循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17439843/

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