为什么char =='L'和char!='L'具有相同的输出?

时间:2015-02-23 18:17:19

标签: java

我想要发生什么:我想将当前值保存到char holder变量。因此,如果当前值!=持有者值,则应该向左移动,但当当前值等于持有者值时,它应向前移动。

问题:char值持有者与其他语句输出相同的内容。 什么假设是问题?

只是根据循环时的方向。

public void reconstructPath(Node node) {
    while (node.parent != null) {
        //DIRECTIONS: L - Left, R - Right, U - up, D - Down
        int nextX, nextY;
        char direction = 0; 
        char current = 0;
        nextX = node.parent.x;
        nextY = node.parent.y;

        if(nextX == node.x)
        {   

            if(nextY > node.y){
                direction = 'D';
            }   
            else{
                direction = 'U';


            }

        }else if(nextY == node.y){  

            if(nextX > node.x){             
                direction = 'R';

            }else{
                direction = 'L';
                if(direction != 'L'){
                    System.out.println("move forward");
                }else{
                    char holder = direction;
                    System.out.println("move up");
                }

            }
        }

        System.out.printf("Traceback: (%d, %d) go %c\n", node.x, node.y, direction);
        node = node.parent;

    }

}

输出:

move L // first L should be left.
Traceback: (4, 1) go L
move L // this should move forward instead of left.
Traceback: (3, 1) go L
move L
Traceback: (2, 1) go L

2 个答案:

答案 0 :(得分:2)

考虑这两个连续的行:

    direction = 'L';
    if(direction != 'L')

你在第一个之后错过了一个近距离大括号吗?

答案 1 :(得分:0)

当您找到" L"时,您必须检查之前的值是否为" L"或不。

要实施此解决方案,您必须记住旧值:

public void reconstructPath(Node node) {
    char lastDirection = (char)-1;
    while (node.parent != null) {
        //DIRECTIONS: L - Left, R - Right, U - up, D - Down
        int nextX, nextY;
        char direction = 0; 
        char current = 0;
        nextX = node.parent.x;
        nextY = node.parent.y;

        if(nextX == node.x)
        {   

            if(nextY > node.y){
                direction = 'D';
            }   
            else{
                direction = 'U';


            }

        }else if(nextY == node.y){  

            if(nextX > node.x){             
                direction = 'R';

            }else{
                direction = 'L';
                if(lastDirection == 'L'){
                    System.out.println("move forward");
                }else{
                    System.out.println("move up");
                }

            }
        }
       lastDirection = direction;
        System.out.printf("Traceback: (%d, %d) go %c\n", node.x, node.y, direction);
        node = node.parent;

    }

}