Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if String Is Not Equal to Something

Tags:

string

c#

console

Here is my code:

using System;

namespace FirstProgram
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            Console.WriteLine ("What is your first name?");
                String Name = Console.ReadLine ();
            Console.WriteLine ("\nHi " + Name + "! Now tell me are you a boy or girl?");
                String Sex = Console.ReadLine ();

            if (!Sex.Equals ("boy") || !Sex.Equals ("girl")) {
                Console.WriteLine ("\nERROR: You were supposed to type 'boy' or 'girl'\nPress any key to exit...");
                Console.ReadKey ();
                System.Environment.Exit (1);
            }

            Console.WriteLine ("\nOk so your name is " + Name + " and your are a " + Sex + "... Please tell me your age :)");
                int Age = Convert.ToInt32 (Console.ReadLine ());
            Console.WriteLine ("\nYou are " + Age + " years old!");
            Console.ReadKey ();
        }
    }
}

I just want to know why the program exits even though I type "boy" or "girl" and how I can fix this.

like image 352
AwkwardMonkey Avatar asked May 28 '26 18:05

AwkwardMonkey


2 Answers

Simple logic:

Sex != "boy" || Sex != "girl"

will always be true.

You need to use

Sex != "boy" && Sex != "girl"

instead.

A few extra notes:

  • C# supports operator overloading and it's commonly used, so you can use == and != for strings just fine.
  • Don't use Environment.Exit, just return. If you need to return an error code, change the signature of Main to int Main() and return 1;. But note that on Windows, applications may assume that an application that returned a non-success code failed in some way and report it - e.g. Total Commander will pop up a message.
  • Don't use \n. Either use Environment.NewLine, or just stick to Console.WriteLine for endlines.
  • Consider using string.Format for slapping together complex strings: string.Format("Your name is {0} and your age is {1}.", Name, Age). If you're on C# 6+, string interpolation is even nicer:$("Your name is {Name} and your age is {Age}.")`.
  • A case insensitive comparison might be more useful for your case - Sex.Equals("boy", StringComparison.CurrentCultureIgnoreCase).
like image 145
Luaan Avatar answered May 30 '26 08:05

Luaan


You need to change your if statement from an "OR" to an "AND":

if (!Sex.Equals ("boy") || !Sex.Equals ("girl"))

An "OR" statement evaluates to true if one of the conditions is filled. So if you enter "boy", then the second statement, !Sex.Equals("girl") is true, therefore it executes the code within the if statement.

Instead, use an "AND" statement, which evaluates to true only if both arguments are true.

if (!Sex.Equals ("boy") && !Sex.Equals ("girl"))
like image 44
user1666620 Avatar answered May 30 '26 08:05

user1666620