glls glls - 1 year ago 109
C# Question

while char.TryParse character validation

I am trying to validate a user input and ensure it is within my character range (3 options a,b or c) I managed to make it work, but I don't quite understand why.

char theCharacter;
Console.WriteLine("{0}", "Enter a,b or c");

while (!char.TryParse(Console.ReadLine(), out theCharacter) || !theCharacter.Equals('a') )
if (theCharacter.Equals('b'))
else if (theCharacter.Equals('c'))
Console.WriteLine("Please chose a valid character(a, b or c).");


I understand (or believe so) that
!char.TryParse(Console.Readline(), out theCharacter

validates that what the user entered a char type, and that
|| !the.Character.Equals('a')
will simply validate that if the statement is not true (the char not equals a) the user will be promterd to enter a,b or c.

However, if i do the following:

while (!char.TryParse(Console.ReadLine(), out theCharacter) || !theCharacter.Equals('a') || !theCharacter.Equals('b') || !theCharacter.Equals('c'))

no matter what my input is, user is stuck in the while loop,
and if i do:

while (!char.TryParse(Console.ReadLine(), out theCharacter) && (!theCharacter.Equals('a') == true || !theCharacter.Equals('b') == true || !theCharacter.Equals('c')== true))

no matter what character I input, it is accepted as 'theCharacter'

could someone explain why the 2 below statements are not working, and if the first statement is actually the way to go?

For my homework, theCharacter has to be a char type, and cant use arrays, or else I would have gone with a string and made things easier.

Answer Source

Your initial condition worked because it only entered the loop if the character wasn't "a" and it only continued the loop if the character was also not "b" or "c", e.g. the loop continues only if the character isn't "a", "b" or "c".

Your second condition, however, is flawed because it repeats the loop for every character which is different from one of the 3: "a", "b", "c" (For example, "a" is different from "b" thus it answers the condition. "m" is different from "a" thus it answers the condition). Every character in the world answers this condition. What you meant to check is that the character isn't "a" and isn't "b" and isn't "c", like so:

!theCharacter.Equals('a') && !theCharacter.Equals('b') && !theCharacter.Equals('c')

And the full code:

    char theCharacter;
    while (!char.TryParse(Console.ReadLine(), out theCharacter) ||
           (!theCharacter.Equals('a') && !theCharacter.Equals('b') && !theCharacter.Equals('c'))) {

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download