0

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
4

2 回答 2

1

正在发生的事情是这样的:

在您的第一个 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;
于 2013-07-03T05:06:49.960 回答
1

我不会在这里开设新课程。您只需要一个方法来进行移动,该方法可以在与主函数相同的文件中创建。如果你真的想要一个类来移动汽车,那么你需要正确地声明它。请记住,类需要公共、私有和构造函数以及该类可以执行的所有方法。将移动方法放在汽车类中也很容易,因为汽车类的一部分应该保存汽车对象的位置。我不知道您是希望它在屏幕上移动还是只是更改位置。如果您想在屏幕上移动,while 循环将起作用。但是,如果您只需要更改位置,那么更改保存汽车位置的私有变量会容易得多;由于评估布尔值需要大量的计算时间,因此编码和运行会更容易。祝你好运。如果你有什么不明白的,请告诉我。

于 2013-07-03T05:09:44.587 回答