【问题标题】:How is this causing an infinite loop?这如何导致无限循环?
【发布时间】:2017-01-28 21:25:43
【问题描述】:

我发现这种方法是我的程序出现问题的根源。它涉及一个名为“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("-");
    }
}

【问题讨论】:

  • 欢迎来到本站!请edit your question澄清一下好吗?您遇到的无限循环是什么? “我的调试器结束”是什么意思?您指的是哪种“检查方法”?谢谢!
  • 你有两个循环。
  • 你有没有尝试过这种方法?
  • 您向我们展示的代码没有明显的问题,但是您没有向我们展示的代码呢? isAttacking() 会发生什么?你怎么知道问题不存在?什么构建theBoard?你怎么知道循环不在数据结构中?
  • 您的循环将在到达null 时终止,但我怎么知道有 null?如果列表中最后一项的.next 指向列表中的其他项怎么办?这种结构称为循环列表。有时,有目的地创造是一件有用的事情。但也许你偶然创造了一个。如果您在循环列表上调用checkAttacking(),它将永远不会返回。在您向我们展示创建列表的代码之前,我们无法知道。

标签: java list loops


【解决方案1】:
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 类型的引用对象“当前”是否为空。 如果您在其他类中创建了对象(您说您做到了),那么您的条件每次都是正确的。所以你有无限循环。

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

【讨论】:

    猜你喜欢
    • 2016-05-01
    • 2015-05-20
    • 2013-06-17
    • 1970-01-01
    • 1970-01-01
    • 2020-08-27
    • 2021-05-07
    • 2012-08-24
    相关资源
    最近更新 更多