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

别说谁变了你拦得住时间么 提交于 2019-12-02 09:41:54

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.

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');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!