Click here to Skip to main content
15,885,048 members
Please Sign up or sign in to vote.
2.80/5 (5 votes)
I want to print my gender using bool and if .

And I wrote that codes
C#
static void Main(string[] args)
       {
           bool male=true;
           string gender;
           Console.WriteLine("Please enter your gender");
           gender = Console.ReadLine();
           if (male!=true)
           {
               Console.WriteLine("Your gender is female");
           }
           else
           {
               Console.WriteLine("Your gender is male");
           }
           Console.ReadLine();
       }

But when I executed this code, return male , why?
Posted
Comments
Timberbird 4-Feb-15 3:56am    
And what do you expect it to return? You assign male variable only once - when it's created. Any user input is stored in gender variable which doesn't affect print output. And since male=true, check if (male!=true) returns false, so Console.WriteLine("Your gender is male"); is executed

Because you are never using the input provided by the user, in your code.

Try:
C#
static void Main(string[] args)
       {
           string gender;
           Console.WriteLine("Please enter your gender");
           gender = Console.ReadLine();
           if (gender == "female")
           {
               Console.WriteLine("Your gender is female");
           }
           else if (gender == "male")
           {
               Console.WriteLine("Your gender is male");
           }
           else
           {
              Console.WriteLine("Your gender is unrecognized");
           }

           Console.ReadLine();
       }
 
Share this answer
 
v2
Comments
goksurahsan 4-Feb-15 3:54am    
Thank you
CPallini 4-Feb-15 5:47am    
You are welcome.
The code is incorrect here.
You are saving user input in a string variable and comparing bool variable male (which is always true).
You need to compare on string variable like:
C#
if(gender == "Male")
  //print male
else if(gender == "Female")
  //print female
else
  //print improper input
 
Share this answer
 
v2
>But when I executed this code, return male , why?
You don't evaluate the input string but only the "bool male" that is allways true!

Try this:

C#
static void Main(string[] args)
{
    //bool male=true;
    string gender;
    Console.WriteLine("Please enter your gender");
    gender = Console.ReadLine();
    //if (male!=true)
    if ( genger == "female" )
    {
        Console.WriteLine("Your gender is female");
    }
    else
    {
        Console.WriteLine("Your gender is male");
    }
    Console.ReadLine();
}
 
Share this answer
 
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900