c# 循环直到 Console.ReadLine = 'y' 或 'n'

c# loop until Console.ReadLine = 'y' or 'n'

我是 c# 的新手,正在练习编写一个简单的控制台应用程序。我希望应用程序提出一个问题,并且仅在用户输入等于 'y' 或 'n' 时才进入下一段代码。这是我目前所拥有的。

static void Main(string[] args)
{

    string userInput;
    do
    {
        Console.WriteLine("Type something: ");
        userInput = Console.ReadLine();
    }   while (string.IsNullOrEmpty(userInput));

    Console.WriteLine("You typed " + userInput);
    Console.ReadLine();

    string wantCount;
    do
    {
        Console.WriteLine("Do you want me to count the characters present? Yes (y) or No (n): ");
        wantCount = Console.ReadLine();
        string wantCountLower = wantCount.ToLower();
    }   while ((wantCountLower != 'y') || (wantCountLower != 'n'));
}

我从 string wantCount; 开始遇到问题。我想做的是询问用户是否要计算字符串中的字符数,然后循环该问题直到输入 'y' 或 'n'(不带引号)。

请注意,我还想满足输入 upper/lower 的情况,所以我想象我想将 wantCount 字符串转换为更低的字符串 - 我知道我目前使用的方式不会像我一样工作在循环内设置 string wantCountLower,所以我不能在 while 子句的循环外引用。

你能帮我理解如何实现这个逻辑吗?

如果你想比较一个字符,那么 ReadLine 不需要它们,你可以使用 ReadKey,如果你的条件是这样的:while ((wantCountLower != 'y') || (wantCountLower != 'n')); 你的循环将是一个无限的,所以你可以在这里使用 && 代替 || 或者它将是 while(wantCount!= 'n') 这样它会循环直到你按下 n

char charYesOrNo;
do
{
   charYesOrNo = Console.ReadKey().KeyChar;
   // do your stuff here
}while(char.ToLower(charYesOrNo) != 'n');

您可以将输入检查移至循环内部并使用 break 退出。请注意,您使用的逻辑将始终评估为 true,因此我已经颠倒了条件并将您的 char 比较更改为 string

string wantCount;
do
{
    Console.WriteLine("Do you want me to count the characters present? Yes (y) or No (n): ");
    wantCount = Console.ReadLine();
    var wantCountLower = wantCount?.ToLower();
    if ((wantCountLower == "y") || (wantCountLower == "n"))
        break;
} while (true);

还要注意 ToLower() 之前的 null-conditional 运算符 (?.)。这将确保在未输入任何内容时不会抛出 NullReferenceException