0

I am currently doing an assignment for my programming subject and we're currently focusing on input validation. My current issue is when checking to see if the user has inputted their gender correctly, (M, m, F or f)

I am using:

Console.Write("Please enter your gender (m) or (f) : ");
        response = Console.ReadLine();
        string gender = response;

        if (gender != "m" || gender != "M" || gender != "f" || gender != "F") 
        {

            Console.WriteLine("Error : Gender must be either : M / m (For Male) or F / f (For Female) ");
            Console.ReadLine();
            Environment.Exit(0);


        }

The console is outputting "Mistake" for absolutely anything that I enter, however, when I remove the last three parts of the condition and leave it as (gender != "M") it seems to work fine.

Ajdin
  • 5
  • 1
  • 1
  • 3
  • 5
    It should be **and** (so `&&` instead of `||`). – Willem Van Onsem Apr 05 '17 at 13:01
  • You could use `if (new[] { "m", "f" }.Contains(gender, StringComparer.InvariantCultureIgnoreCase)){ ... }` – Tim Schmelter Apr 05 '17 at 13:02
  • Look into logic gates – FakeCaleb Apr 05 '17 at 13:02
  • Just follow your code. What happens if the user entered "m"? The first condition in your `if` statement `gender != "m"` will be `false`. Because you're using or (`||`), then it continues to the next condition (`gender != "M"`) which is `true`. Since `or` short circuits, it will enter the if block if any of the conditions are true. In other words: `(false || true || true || true) == true` – Chris Dunaway Apr 05 '17 at 14:40

0 Answers0