Java新手在这里。我有多个 while 循环。所有人都认为它会按顺序下降,直到 while 条件等于 true。我的输出表明它会执行它发现的第一个 while 循环,然后退出,而不查看其他循环。请告知是否有更好的方法来执行此操作,或者您是否看到明显的错误。(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);
}
方法 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