Someguywhocodes
Someguywhocodes

Reputation: 781

Java: Check if current item in loop is the last item within the Stack being looped

I have the following:

public Move nextBestMove(Stack<Move> possibleMoves, Stack<Square> enemyPieces){

    int highestWeight;
    Move best = null;

    for(Move move: possibleMoves){
        Square landing = move.getLanding();
        int landingX = move.getLandingXC();
        int landingY = move.getLandingYC();

        int score = scoring(enemyPiece.pieceName()){
            if(score > highestWeight){
                highestWeight = score;
                best = move;
                if(!possibleMoves.hasNext()){ //Check if i am at end of stack
                    return best;
                else{
                    continue;
                }
            }
        }
    }
}

I'm trying to evaluate the best move to make in a simple chess strategy implementation, by continually updating the best move based on weighting. However I'm unsure how to check if I am at the last item in my loop through a stack.

I know I can use .hasNext() for a list but how can I accomplish similar with a loop through Stack?

Upvotes: 1

Views: 289

Answers (2)

Naman
Naman

Reputation: 32028

What you need to check is, if its size is 1

if(possibleMoves.size() == 1) { //Checking the size of the stack currently
    return best;
} else {
    continue;
}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726889

You don't need to check for the last item in the loop, because the loop is about to finish anyway. Once the loop finishes, return unconditionally:

for(Move move: possibleMoves){
    Square landing = move.getLanding();
    int landingX = move.getLandingXC();
    int landingY = move.getLandingYC();
    int score = scoring(enemyPiece.pieceName());
    if(score > highestWeight){
        highestWeight = score;
        best = move;
    }
}
return best;

Upvotes: 1

Related Questions