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?
If you want to compare a character, then their is not need for
ReadLine
you can useReadKey
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 bewhile(wantCount!= 'n')
so that it will loops until you pressn
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 totrue
so I've inverted the condition as well as changed yourchar
comparison to astring
.Also note the null-conditional operator (
?.
) beforeToLower()
. This will ensure that aNullReferenceException
doesn't get thrown if nothing is entered.