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

标签 java while-loop conditional-statements multiple-conditions

这里是 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/

相关文章:

java - 监听数据,while(true) 是正确的解决方案吗? java

java - Java中的多维数组条件

c - 如果有条件,多行的良好C编码样式

java - 在字符串前添加空格 - 不像我想象的那样起作用

java - 远程管理接口(interface) : NotBoundException

javascript - 如何在 while 循环中检查事件?

javascript - 为什么我的 while 循环没有完全迭代?

java - 使用 spring 的 Wicket WebApplication/WebPage 循环依赖

java - 如何使用 Maven 的 Java API 访问 Maven Artifact POM?

java - 为什么我必须使用相同的对象来同步和调用等待/通知,但使用类 Condition 我可以使用不同的对象?