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

2019-03-03 15:11发布

问题:

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'));


    }

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.

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?

回答1:

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);

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



回答2:

If you want to compare a character, then their is not need for ReadLine you can use ReadKey for that, if your condition is this :while ((wantCountLower != 'y') || (wantCountLower != 'n')); your loop will be an infinite one, so you can use && instead for || here or it will be while(wantCount!= 'n') so that it will loops until you press n

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