【发布时间】:2015-06-04 09:20:02
【问题描述】:
所以,之前我发布了一个问题,询问如何通过字符数组运行字符串以使每个字母等于数组中的单独字符值。
我尝试使用 foreach 循环,然后将数组中的每个对象标记为“Guess”,然后根据用户输入的值测试每个值,但是我不知道如何在循环结束时输出 if用户输入了一个错误的值。而不是每次值对数组值为假时输出,因为循环旨在为每个值做一些事情。
所以我有点卡住了。我认为有一种方法可以用 for 循环来做到这一点,但我还是有点笨。我想知道是否有人可以帮助我。
char letter;
int score = 0;
string hangWord;
//input inputs
Console.WriteLine("Welcome to the hangman game!");
Console.WriteLine();
Console.WriteLine();
Console.WriteLine();
Console.WriteLine("Player 1 please enter a word.");
hangWord = Convert.ToString(Console.ReadLine());
char[] hangCharacters = hangWord.ToCharArray();
char[] asteriskWord = hangWord.ToCharArray();
string displayWord;
foreach (char guess in asteriskWord)
{
asteriskWord[guess] = '*';
}
while (score < 5)
{
Console.WriteLine("Enter a letter please");
Console.WriteLine();
foreach (char guess in hangCharacters)
{ //How do I write a loop that tests all values and if none are correct
//displays "You guessed incorrectly"?
letter = Convert.ToChar(Console.ReadLine());
if( guess == letter)
{
Console.WriteLine("You guessed correctly!");
Console.WriteLine
//Also I don't know how to change the correct value in the asteriskWord[] so that it displays
//only the character that was guessed in asteriskWord[]
}
}
}
Console.WriteLine("Your score is " + score);
if (displayWord == hangWord)
Console.WriteLine("You Win! Thank you for playing!");
else
{
Console.WriteLine("Thank you for playing! Try again!");
}
【问题讨论】:
-
不要在一种单一的方法中塞满所有东西。分解你的实现。
标签: c# arrays loops for-loop foreach