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

后端 未结 2 497
醉话见心
醉话见心 2021-01-24 10:52

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 eq

相关标签:
2条回答
  • 2021-01-24 11:19

    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.

    0 讨论(0)
  • 2021-01-24 11:20

    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');
    
    0 讨论(0)
提交回复
热议问题