c# 循环直到 Console.ReadLine = 'y' 或 'n' [英] c# loop until Console.ReadLine = 'y' or 'n'

查看:23
本文介绍了c# 循环直到 Console.ReadLine = 'y' 或 'n'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 c# 还很陌生,正在编写一个简单的控制台应用程序作为练习.我希望应用程序提出一个问题,并且只有在用户输入等于y"或n"时才进入下一段代码.这是我目前所拥有的.

I'm fairly new to c#, and writing a simple console app as practice. I want the application to ask a question, and only progress to the next piece of code when the user input equals 'y' or 'n'. Here's what I have so far.

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'(不带引号).

I'm having trouble from string wantCount; onwards. What I want to do is ask the user if they want to count the characters in their string, and loop that question until either 'y' or 'n' (without quotes) is entered.

请注意,我还想满足输入的大写/小写的需求,所以我想将 wantCount 字符串转换为小写 - 我知道我目前的设置方式不起作用 string wantCountLower 在循环内,所以我不能在 while 子句中在循环外引用.

Note that I also want to cater for upper/lower case being entered, so I image I want to convert the wantCount string to lower - I know that how I currently have this will not work as I'm setting string wantCountLower inside the loop, so I cant then reference outside the loop in the while clause.

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

Can you help me understand how I can go about achieving this logic?

推荐答案

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

You could move the input check to inside the loop and utilise a break to exit. Note that the logic you've used will always evaluate to true so I've inverted the condition as well as changed your char comparison to a 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() 之前的空条件运算符 (?.).这将确保在没有输入任何内容时不会抛出 NullReferenceException.

Also note the null-conditional operator (?.) before ToLower(). This will ensure that a NullReferenceException doesn't get thrown if nothing is entered.

这篇关于c# 循环直到 Console.ReadLine = 'y' 或 'n'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆