I'm having some trouble with a chess program. My validMove method does not work correctly. It's forcing all the pieces to move like a king. I think it has something to do with the way I'm passing String piece to the function, but everything I have tried to fix it has not worked.
Your immediate problem is that you are comparing String values incorrectly. This:
compares to String references to see if they refer to the same object. If instead you want to compare two String references to see if their String objects contain the same sequence of characters -- which they could do even if they are two different String objects -- then do this:
I could go on and suggest that your idea of using Strings to represent your pieces is short-sighted. Instead you could have a Piece class which implements the validMove() method, with subclasses for each of the types of piece each of which implements that method in the appropriate way. But that's perhaps something to do for Version 2 of the game.
posted 8 years ago
That might help when the correct variable reaches the validMove mehtod. The problem is that the validMove method always gets piece as null. Since it doesn't match any of the strings, it treats the piece as a king.