简体   繁体   English

验证用户输入是字母表中的一个字母

[英]Validating that user input is a letter of the alphabet

I am trying to make a hangman game where it picks a random word from a text file of words.我正在尝试制作一个刽子手游戏,它从单词的文本文件中随机选择一个单词。 It then displays the word in asterisks and asks the user to guess each letter of the word if they guess right it uncovers that letter.They keep playing until they guess all the letters in the word.After the word is guessed it will display the number of misses and ask if they want to play again.然后它以星号显示单词,并要求用户猜出单词的每个字母,如果他们猜对了,就会发现那个字母。他们继续玩,直到他们猜出单词中的所有字母。猜出单词后,它会显示数字未命中并询问他们是否想再玩一次。

The Problem I am having is that I am trying to validate that the user entered a single character and that it is a letter of the alphabet but when the user puts in a single letter it just starts a infinite loop.not sure how to fix this.我遇到的问题是我试图验证用户输入了一个字符并且它是字母表中的一个字母但是当用户输入一个字母时它只是开始一个无限循环。不知道如何解决这个问题.

 static void Main(string[] args)
    {
        char[] guessed = new char[26];
        char guess = ' ';
        char playAgain= ' ';
        bool validLetterInput = false;
        bool validAnswer = false;


        int amountMissed = 0, index = 0;

        do
        {
            // initilization of word and testword so that we could generate a testword with the same length as original
            char[] word = RandomLine().Trim().ToCharArray();

            char[] testword = new string('*', word.Length).ToCharArray(); 
            char[] copy = word;

            Console.WriteLine(testword);
            Console.WriteLine("I have picked a random word on animals");
            Console.WriteLine("Your task is to guess the correct word");


            while (!testword.SequenceEqual(word))
            {
                while (!validLetterInput)
                {
                    try
                    {
                        Console.Write("Please enter a letter to guess: ");
                        guess = char.Parse(Console.ReadLine().ToLower());
                        //Checks if guess is letter or not
                        if (((guess >= 'A' && guess <= 'Z') || (guess >= 'a' && guess <= 'z')))
                        {
                            validLetterInput = true;
                        }
                        else
                        {
                            Console.WriteLine("Invalid Input");
                        }


                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.Message);

                    }
                }

                bool right = false;
                for (int j = 0; j < copy.Length; j++)
                {
                    if (copy[j] == guess)
                    {
                        Console.WriteLine("Your guess is correct.");
                        testword[j] = guess;
                        guessed[index] = guess;
                        index++;
                        right = true;
                    }
                }
                if (right != true)
                {
                    Console.WriteLine("Your guess is incorrect.");
                    amountMissed++;
                }
                else
                {
                    right = false;
                }
                Console.WriteLine(testword);

            }
            Console.WriteLine($"The word is {string.Join("",testword)}. You missed {amountMissed} times.");
            while (!validAnswer)
            {
                try
                {
                    Console.WriteLine("Do you want to guess another word? Enter y or n: ");
                    playAgain = char.Parse(Console.ReadLine());
                    if(playAgain == 'y' || playAgain == 'Y' || playAgain == 'n' || playAgain == 'N')
                    {
                        validAnswer = true;
                    }
                    else
                    {
                        Console.WriteLine("Invalid input try again");
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                }
            }
        } while (playAgain == 'y' || playAgain == 'Y');


        Console.WriteLine("Good-Bye and thanks for playing my Hangman game.");
    }
        public static string RandomLine()
    {

            // store text file in an array and return a random value
            string[] lines = File.ReadAllLines("E:\\Advanced1.csv");
            Random rand = new Random();
            return lines[rand.Next(lines.Length)].ToLower();



    }
}

You just have to add one line.你只需要添加一行。 After checking the letter and printing the testword, reset validLetterInput to false, so that it can get the next letter.检查字母并打印测试词后,将validLetterInput重置为false,以便它可以获取下一个字母。

if (right != true)
{
    Console.WriteLine("Your guess is incorrect.");
    amountMissed++;
}
else
{
    right = false;
}
Console.WriteLine(testword);
validLetterInput = false;

It seems like you are not resetting the validLetterInput to false after first validation.在第一次验证后,您似乎没有将 validLetterInput 重置为 false。


while (!testword.SequenceEqual(word))
{
    while (!validLetterInput) // <-- Need to reset this after first correct validation
    {
        try
        {
            Console.Write("Please enter a letter to guess: ");
            guess = char.Parse(Console.ReadLine().ToLower());
            //Checks if guess is letter or not
            if (((guess >= 'A' && guess <= 'Z') || (guess >= 'a' && guess <= 'z')))
            {
                validLetterInput = true;
            }
            else
            {
                Console.WriteLine("Invalid Input");
            }


        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);

        }
    }
    validLetterInput = false; // <--- ADD THIS HERE

After the first letter is accepted as valid character, it is never reset for the next letter.在第一个字母被接受为有效字符后,它永远不会为下一个字母重置。 Once you exit the while loop where you are checking for valid input, reset the validLetterInput to false退出检查有效输入的 while 循环后,将 validLetterInput 重置为 false

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM