【问题标题】:C#, Validating user input for letters and whitespace using booleanC#,使用布尔值验证用户输入的字母和空格
【发布时间】:2021-01-14 21:34:12
【问题描述】:

我正在制作一个反转字符串的程序,并且除了字母和空格之外不允许任何其他内容,问题是如果我输入无效输入然后尝试输入有效输入它只会保持打印错误.我认为这个问题与我的 while 循环和 bool 结果有关,但我无法弄清楚。请帮忙,谢谢!

        static void Reverse()
        {
            string name;
            Console.Write("Enter your name: ");
            name = Console.ReadLine();

            bool result = name.All(c => char.IsWhiteSpace(c) || char.IsLetter(c));
            if (Regex.IsMatch(name, @"^[a-zA-Z- ]+$"))  // Validates the input for characters and/or spaces
            {
                char[] charArr = name.ToCharArray();
                Array.Reverse(charArr);
                string nameRev = new string(charArr);
                Console.WriteLine("String is {0}", nameRev);
            }
            else
            {
                while (name == String.Empty || result == false) //Should validate the input for whitespace or letter if it doesn't pass the first validation
                {
                    Console.Write("Error! Enter your name, only letters allowed: ");
                    name = Console.ReadLine();
                }
            }

【问题讨论】:

  • 问题是你从来没有在while循环中将结果设置为true,所以如果第一次迭代不正确,你永远不会离开。

标签: c# input while-loop boolean


【解决方案1】:

您需要将 while 循环包裹在孔序列周围,而不是仅将其放在 else 语句中。

示例:

static void Reverse()
{
    // Continues executing as long as result stays false.
    bool result;
    do 
    {
        string name;
        Console.Write("Enter your name: ");
        name = Console.ReadLine();

        result = name.All(c => char.IsWhiteSpace(c) || char.IsLetter(c));
        if (Regex.IsMatch(name, @"^[a-zA-Z- ]+$"))
        {
            char[] charArr = name.ToCharArray();
            Array.Reverse(charArr);
            string nameRev = new string(charArr);
            Console.WriteLine("String is {0}", nameRev);
        }
        else 
        {
            Console.WriteLine("Error! Only letters allowed");
        }
    }
    while (!result);
}

【讨论】:

  • 感谢您的提示,我现在看到了问题,我会继续尝试找出自己的解决方案!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-17
  • 2020-07-19
  • 1970-01-01
  • 2015-01-31
  • 1970-01-01
  • 1970-01-01
  • 2023-03-29
相关资源
最近更新 更多