I’m working on a self directed simple program to practice concepts I’ve learned thus far. My project is related to chess, in this case specifically the board (columns a-h and rows 1-8). The user is asked for the current location of a specific chess piece hopefully entered as a letter for the column followed by a number for the row. To validate this it made sense to me to first check if this value was entered as a string of two characters, otherwise what is entered is already incorrect. I then converted the entered string to lower case characters before comparing it with my list of acceptable array elements.
From searching this site I get the impression that a string stores its characters as an array and using the char property of string you would be able to pull off the first character thus comparing char to char. I have not yet found anything specific enough in my searches to really give me a good understanding of what is happening. This is the closest option I’ve come across which I didn’t feel was applicable to this case. Any insight would be appreciated.
The code that follows produces the following error.
Operator ‘==’ cannot be applied to operands of type ‘char’ and ‘string’
private char[] gridColumns = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', };
private void createMoveButton_Click(object sender, RoutedEventArgs e)
{
// Assigns text box input to associated private fields
this.gameId = this.gameIdTextBox.Text;
this.playerId = this.playerIdTextBox.Text;
this.gamePiece = this.gamePieceTextBox.Text;
this.currentLocation = this.currentLocationTextBox.Text;
this.targetLocation = this.targetLocationTextBox.Text;
// Current location should only ever be 2 characters, ensure from the start this is true.
if (currentLocationTextBox.Text.Length == 2)
{
// Converts contents of currentLocationTextBox to lower case characters for comparison.
string cl = currentLocation.ToLowerInvariant();
// Iterates through my array of possible column choices
for (int i = 0; i < gridColumns.Length; i++)
{
Char.ToLowerInvariant(currentLocationTextBox.Text[0]);
// Trying to compare the first character of my string to the char element of my array.
if (cl[0] == gridColumns[i])
{
//TODO
}
}
}
else
{
MessageBox.Show("Check your starting location. It needs to be a lower case character variable (a-h) followed by a number (1-8)");
}
}
See Question&Answers more detail:os