【发布时间】:2013-10-12 20:40:54
【问题描述】:
我正在开发一个自我指导的简单程序来练习我迄今为止学到的概念。我的项目与国际象棋有关,在这种情况下特别是棋盘(a-h 列和 1-8 行)。要求用户输入特定棋子的当前位置,希望将其输入为列的字母,后跟行的数字。 为了验证这一点,我首先检查这个值是否输入为两个字符的字符串,否则输入的内容已经不正确。 然后,我将输入的字符串转换为小写字符,然后将其与可接受的数组元素列表进行比较。
通过搜索此site,我得到的印象是字符串将其字符存储为数组,并使用字符串的char 属性,您将能够提取第一个字符,从而将char 与char 进行比较。在我的搜索中,我还没有找到任何足够具体的东西来真正让我对正在发生的事情有一个很好的了解。 This 是我遇到的最接近的选项,但我觉得不适用于这种情况。任何见解将不胜感激。
下面的代码会产生以下错误。
运算符“==”不能应用于“char”类型的操作数和 ‘字符串’
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)");
}
}
【问题讨论】:
-
我在你的代码中看到了
string gamePiece,但我没有看到数组gamePieces。您是否将两者混淆了,或者它真的是其他地方的单独数组?
标签: c# .net arrays string char