do-while循环在条件C#时没有通过

问题描述 投票:-5回答:3

我写了一个do-while循环,但它不会以某种方式通过while条件。当我输入无效字符时,它应该回到开头并按原样重复。我在Visual Studio上逐步运行了代码,它显示代码甚至没有通过while条件。 (无论输入值是多少)有人可以帮帮我吗?提前非常感谢!

using System;
using static System.Console;

namespace a5
{
    class Program
    {
        const string acceptedLetters = "EHLNTXZ";

        static void Main(string[] args)

        {
            GetUserString(acceptedLetters);
            ReadKey();
        }

        static string GetUserString(string letters)
        {
            string invalidCharacters;
            do
            {
                invalidCharacters = null;

                Write("Enter : ");

                string inputCharacters = ReadLine();

                foreach(char c in inputCharacters) 
                {
                    if(letters.IndexOf(char.ToUpper(c))==-1)
                    {
                        invalidCharacters = c.ToString();
                    }
                }

                if(invalidCharacters != null)
                {
                    WriteLine("Enter a valid input");
                }
                return inputCharacters;
            } while (invalidCharacters != null);


         } 
    }
}
c# loops while-loop do-while
3个回答
0
投票

问题是,无论验证完成,您都将在循环末尾返回输入的字符串。

您可以使用布尔值检查此有效性。

此外,您不需要解析所有字符串,并且可以在第一个无效字符上中断内部循环。

我将字符串重命名为result以使用标准模式并更加简洁。

例如:

static string GetUserString(string letters)
{
  string result;
  bool isValid;
  do
  {
    Console.Write("Enter : ");
    result = Console.ReadLine();
    isValid = true;
    foreach ( char c in result )
      if ( letters.IndexOf(char.ToUpper(c)) == -1 )
      {
        isValid = false;
        Console.WriteLine("Enter a valid input");
        break;
      }
  }
  while ( !isValid );
  return result;
}

0
投票

[C0行使它离开循环。

我想你是说:

return inputCharacters;

-1
投票
} while (invalidCharacters != null);
return inputCharacters; 
© www.soinside.com 2019 - 2024. All rights reserved.