【问题标题】:Hangman Game iterating over arrays with the for loop in C#Hangman Game 使用 C# 中的 for 循环遍历数组
【发布时间】: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


【解决方案1】:

在 foreach 之前将 bool 标志设为 false,仅当字母匹配时,在 foreach 内部将其设为 true,否则将保持 false。在迭代后测试条件并根据标志状态显示消息。

【讨论】:

  • 谢谢,这很有意义!我会投票赞成您的评论,但我仍然是菜鸟。我还需要 4 个代表大声笑,但我会记住你的。
【解决方案2】:

你可以稍微改变你的逻辑,看看猜测是否在挂起的字符中。此刻,你只检查用户输入的字母是否是当前迭代的字母

letter = Convert.ToChar(Console.ReadLine());
if(hangCharacters.Any(c => c == letter))
    Console.WriteLine("You guessed correctly!");
else
    Console.WriteLine("You guessed incorrectly!");

要使用上述内容,您需要包含System.Linq

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 2017-01-02
    • 2016-01-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多