简体   繁体   中英

How is this causing an infinite loop?

I have found this method to be the source of my problems for my program. It involves a linked list called 'theBoard' with chesspiece objects in it. When stepping through my debugger, my debugger ends when it hits this checking method. Anyone know what's the problem with it?

EDIT: This method checks if one chesspiece in the linked list can attack another chesspiece in the linked list. It takes theBoard (the linked list object created in another class where pieces were added) as a parameter.

the method '.isAttacking' checks if one piece can attack the other (method in each piece class, each piece class extending an abstract "chessPiece" class).

Am I doing something wrong? I'm using Intellij debugger and going line by line. Once I hit this method call, the debugger seems to stop.

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);
        }
    }
}

This is my sample of the code. The result is 100x "Welcome" text. I think that you have the same problem.

 while (current != null)

In your loop you check if the reference object "current" of type LinkedList is null or not. If you have created object in other class(you said that you did it) your contidtion is every time true. So you have infinite loop.

If you want to check every object in current list, I propose to use Iterator and hasNext(),next() method or for-each loop. See you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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