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