限制用户输入y或n并在C#中相应地显示结果

时间:2016-07-01 08:46:04

标签: c# loops boolean-logic

我正在编写一个代码,要求用户提供他的名字,以及他是否想读一个笑话。答案应限于y或n。任何其他字符都应被视为无效,并应循环回问题。这是我到目前为止所做的。

    static void Main(string[] args)
    {
        string name="";
        string KeyChar;

        Console.WriteLine("Hello, what is your name?");
        name=Console.ReadLine();

        Console.WriteLine("Greetings, " + name + ". Would you like to read a joke? (y/n)");

        ConsoleKeyInfo result = Console.ReadKey();
        Console.WriteLine("\n");

        while (true)
        {

            while ((result.KeyChar != 'Y') || (result.KeyChar != 'y') || (result.KeyChar != 'N') || (result.KeyChar != 'n'))
            {
                Console.WriteLine("Invalid key. Limit your answer to y or n");
                break;
            }

            while ((result.KeyChar == 'Y') || (result.KeyChar == 'y') || (result.KeyChar == 'N') || (result.KeyChar == 'n'))
            {
                if ((result.KeyChar == 'Y') || (result.KeyChar == 'y'))
                {
                    Console.WriteLine("Joke question?");
                    Console.ReadLine();
                    Console.WriteLine("Joke answer.");
                    break;
                }
                else if ((result.KeyChar == 'N') || (result.KeyChar == 'n'))
                {
                    Console.WriteLine("You're missing on all the fun! Suit yourself. Goodbye!");
                    break;
                }

            }
        }

    }

1 个答案:

答案 0 :(得分:0)

你最好写一个单独的方法来询问Y或N,例如:

public static char YorN(string prompt)
{
    Console.Write(prompt + " ");

    while (true)
    {
        char input = char.ToUpper(Console.ReadKey().KeyChar);

        if (input == 'Y' || input == 'N')
        {
            Console.WriteLine();
            return input;
        }

        Console.Write("\b \b"); // Use backspace ('\b') to erase the incorrect character.
    }
}

然后你不需要在循环中调用它:

Console.WriteLine("Hello, what is your name?");
string name = Console.ReadLine();

char response = YorN("Greetings, " + name + ". Would you like to read a joke? (y/n)");

if (response == 'Y')
{
    Console.WriteLine("Joke question?");
    Console.ReadLine();
    Console.WriteLine("Joke answer.");
}
else
{
    Console.WriteLine("You're missing on all the fun! Suit yourself. Goodbye!");
}