You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

仅用循环实现C# Hangman猜词游戏:添加猜词对错提示问题

解决C# Hangman猜词游戏的提示语句问题

你当前的问题出在错误提示的判断逻辑上:第二个for循环只要遇到一个和输入字母不匹配的字符,就会立刻输出错误提示并终止循环——哪怕输入的字母在单词里存在,只要有一个字符不匹配就会触发错误提示,这显然不符合需求。

正确的做法是先遍历单词,判断输入的字母是否存在,用一个布尔变量记录结果,遍历完成后再根据这个变量输出对应的提示。以下是修改后的完整代码:

static void Main(string[] args)
{
    Console.WriteLine("Welcome to Hangman!!!!!!!!!!");
    string[] listwords = new string[10] 
    {"sheep", "goat","computer","america","watermelon","icecream",
    "jasmine","pineapple","orange","mango"};

    Random randGen = new Random();
    var idx = randGen.Next(0, 9);
    string mysteryWord = listwords[idx];
    char[] guess = new char[mysteryWord.Length]; 
    for (int p = 0; p < mysteryWord.Length; p++)
    {
        guess[p] = '*';
        Console.Write(guess[p]);
    }

    Console.WriteLine();

    while (true)
    {
        Console.WriteLine("Please enter your guess: ");
        char playerGuess = char.Parse(Console.ReadLine());
        bool isGuessCorrect = false; // 标记是否猜中字母

        // 遍历单词,更新已猜中字符并标记是否猜中
        for (int j = 0; j < mysteryWord.Length; ++j)
        {
            if (playerGuess == mysteryWord[j])
            {
                guess[j] = playerGuess;
                isGuessCorrect = true; // 只要找到一个匹配就设为true
            }
        }

        // 根据标记输出对应提示
        if (isGuessCorrect)
        {
            Console.WriteLine("Yes! There is {0} in the word", playerGuess);
        }
        else
        {
            Console.WriteLine("There is no {0} in the word", playerGuess);
        }

        Console.Write(guess);
        Console.WriteLine();

        string guessString = new string(guess);
        if (guessString == mysteryWord)
        {
            Console.Write("You win! The word is {0}", guessString);
            Console.WriteLine();
            return;
        }
    }
}

修改关键点说明

  • 新增bool isGuessCorrect = false;变量,专门用来记录当前输入的字母是否在单词中存在
  • 在遍历单词的循环里,只要找到匹配的字符,就将isGuessCorrect设为true——哪怕单词里有多个相同字符,这个标记只会被设为true一次
  • 遍历完成后,统一根据isGuessCorrect的值输出提示,避免了循环中误判的问题
  • 现在不管输入正确还是错误,只会输出一次对应的提示,符合需求

内容的提问来源于stack exchange,提问作者diogenes31

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 11:35:42