iDevDecipher iDevDecipher - 15 days ago 8
Java Question

Why does .equals() fail??? Checkers Game

I am currently working on a checkers game for a school project. The board is a 2 dimensional array of strings to represent the pieces on the board. Currently I am coding the rules for the game but for some reasons

.equals()
fails in the while loop.

private static String redPawn = "redPawn";
private static String blackPawn = "blackPawn";
private static String redKing = "redKing";
private static String blackKing = "blackKing"
private static String[][] checkerPieces = new String[row][col];

while(!redPawn.equals(checkerPieces[r][c]) || !redKing.equals(checkerPieces[r][c]))
{
System.out.println("You can only move the red pawns");
playerInput.selectPiece();
}


When debugging and putting only:

while(!redPawn.equals(checkerPieces[r][c]))
{
System.out.println("You can only move the red pawns");
playerInput.selectPiece();
}


It works until I add the conditional statement checking for a
redKing
. Can anyone help.

Answer

for some reasons .equals() fails in the while loop.

This is because you use OR ||, use AND && instead

while(!redPawn.equals(checkerPieces[r][c]) && !redKing.equals(checkerPieces[r][c]))