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

查看:287
本文介绍了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天全站免登陆