无法找到无限循环的原因

时间:2017-01-28 06:53:01

标签: java loops

我的代码导致无限循环,我无法找到它并且它让我疯狂。对此有何帮助?它必须采用以下三种方法之一。它涉及一个链表。任何帮助都是极好的。感谢

 public boolean checkNotSamePlacements() {

    Link current = head;

    while (current != null) {

        Link current2 = head;

        while (current2 != null) {

            if (current != current2) {

                if (current.piece.col == current2.piece.col && current.piece.row == current2.piece.row) {

                    return true;
                }
            }
            current2 = current2.next;
        }
        current = current.next;
    }

    return false;
}


public void checkAttacking () {
    boolean foundPieces = false;
    Link current = head;

    while (current != null) {

        Link current2 = head;
        while (current2 != null) {

            if (current != current2) {

                if ((current.piece.isAttacking(current2.piece)) && foundPieces == false) {

                    System.out.print(current.piece.pieceType + " " + current.piece.col +
                    " " + current.piece.row + " " + current2.piece.pieceType +
                    " " + current2.piece.col + " " + current2.piece.row);
                    foundPieces = true;
                }
            }
            current2 = current2.next;
        }
        current = current.next;
    }
    if (foundPieces == false) {
        System.out.print("-");
    }
}

public void checkSpotFound (int col, int row) {

    boolean foundPiece = false;
    Link current = head;

    while (current != null) {

        if (current.piece.col == col && current.piece.row == row) {

            System.out.print(current.piece.pieceType);

            foundPiece = true;
        }
    }

    if (foundPiece == false) {
        System.out.print("-");
    }
}

}

1 个答案:

答案 0 :(得分:2)

代码中的current永远不会更新 -

while (current != null) {

    if (current.piece.col == col && current.piece.row == row) {

        System.out.print(current.piece.pieceType);

        foundPiece = true;
    }

    current = current.next; // you might want to add this to your code
}