首页 > 解决方案 > 允许用户只输入字符串作为答案

问题描述

我想让一个用户只被允许输入字母,这是我到目前为止所尝试的,但是当用户输入一个数字或其他任何东西时,控制台应用程序就会继续。

 static public string Ask(string question)
    {
        do
        {
            Console.Write(question);
            return Console.ReadLine();

        } while (Regex.IsMatch(Console.ReadLine(), @"^[a-zA-Z]+$"));

    }

先感谢您。

标签: c#asp.net.net

解决方案


问题是您正在返回 first 的结果,Console.ReadLine()因此您的循环永远不会继续到while子句。

您需要做的是创建一个字符串变量并分配值,然后在您的 while 子句中检查它:

public static string Ask(string question)
{
    string input;
    do
    {
        Console.Write(question);

        //Assigns the user input to the 'input' variable
        input = Console.ReadLine();

    } //Checks if any character is NOT a letter 
    while (input.Any(x => !char.IsLetter(x)));

    //If we are here then 'input' has to be all letters
    return input;
}

请注意,我也在使用 LinqAny()而不是 Regex。对我来说似乎更容易,而且可能更快(懒得基准测试)。

在这里提琴


推荐阅读