繁体   English   中英

这如何导致无限循环?

[英]How is this causing an infinite loop?

我发现这种方法是我的程序出现问题的根源。 它涉及一个名为“theBoard”的链表,其中包含棋子对象。 单步调试我的调试器时,我的调试器在遇到此检查方法时结束。 有谁知道它有什么问题?

编辑:此方法检查链表中的一个棋子是否可以攻击链表中的另一个棋子。 它以 theBoard(在另一个添加了棋子的类中创建的链表对象)作为参数。

方法 '.isAttacking' 检查一个棋子是否可以攻击另一个(每个棋子类中的方法,每个棋子类扩展一个抽象的“chessPiece”类)。

难道我做错了什么? 我正在使用 Intellij 调试器并逐行进行。 一旦我点击了这个方法调用,调试器似乎就停止了。

public void checkAttacking (chessBoard theBoard) throws FileNotFoundException {

    boolean foundPieces = false;
    Link current = theBoard.head;

    while (current != null) {

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

            if (current != current2) {

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

                   System.out.println(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("-");
    }
}
import java.util.LinkedList;
public class Test {
    public static void main(String[] args) {
        LinkedList list=new LinkedList<>();
        int i=0;
        while(list!=null){
            System.out.println("Welcome");
            i++;
            if(i>100)
                System.exit(0);
        }
    }
}

这是我的代码示例。 结果是 100 倍的“欢迎”文本。 我认为你有同样的问题。

 while (current != null)

在您的循环中,您检查 LinkedList 类型的引用对象“当前”是否为空。 如果你在其他类中创建了对象(你说你做到了),你的 contidtion 每次都是正确的。 所以你有无限循环。

如果要检查当前列表中的每个对象,我建议使用 Iterator 和 hasNext(),next() 方法或 for-each 循环。 再见。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM