0
Is there a way to set a user input to a variable to then be called on?
static void Main(string[] args) { int male; int female; string yourSex; Console.WriteLine("Are you male or female?"); male = 0; female = 1; yourSex = Console.ReadLine(); Console.WriteLine(" Your a {0}",yourSex); if (yourSex = male) { return ("Hello sir"); if (yourSex = female) return("Hello Miss") } }
7 ответов
+ 5
male and female are ints, but yourSex is a string. They can't be compared correctly. 0 and 1 as numbers are different than "0" and "1" as text strings.
To fix this, make male and female strings and set them to "0" and "1", respectively, or "M" and "F" or something similar. Make sure to add the quotes to make them strings!
Second, return shouldn't be used in the ifs. Use Console.WriteLine() to print out your message.
Lastly, there's extra curly braces - one in the if and one after.
+ 2
Your trying to compare a string to an int. In order to do a string comparison in C# you need to use the Equals () method.
If you're wanting to use an int then you need to convert the input type to int Convert.ToInt32 ().
So either use:
Convert.ToInt32(yourSex) == male
or
yourSex.Equals(male) // where male is a string not an int
also when making comparisons use the double equals == not a single = like you have in your if statement. This would actually be trying to assign an int to a string variable.
+ 1
@CarnageCode
See here:
https://goo.gl/Tegjp7
Enter either male or female at the prompt.
Is this what you're after?
OR here:
https://goo.gl/gPAzHS
Enter 0 for male or 1 for female at the prompt.
0
as you can see I am trying to get input of male or female and then use their input to call an if statement to then state ("Hello Miss") or ("Hello Sir") but I come across a error that won't allow me to set a string to a variable, is there a way to make this work?
0
convertToInt32 then use boolean to asign. Make 0 male and 1 female. Many ways to achieve this.
0
Thank you all but I am missing something at isn't allowing me to achieve my end goal for it to say hello Miss or Sir, I took out the extra brackets. I've changed to Convert.ToInt32 (yourSex) == male and I changed my male = 1; and female to "female" and "male" but now I'm getting a communication error from that I believe is from me not calling an additional statement like a boolean but I don't know very much about the boolean only that they are true and false statements and more but I don't know how calling them works properly.
0
I see, guess there isn't a way to get around having to put in numbers to get word answers