Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Thursday, January 12, 2012 11:50 PM
I was wondering why this wouldn't work.
I wanted to make the code only accept letters m , M , f , f. So i tried to run the code and enter another letter , it still would accept other letters that are not supposed to be accepted.
get {return gender;}
set{
if (value !='F' && value !='M' && value !='m' && value !='f');
{
Console.WriteLine("Invalid Gender. Please input again.");
Console.WriteLine("Input Gender: ");
value= Convert.ToChar(Console.ReadLine());
gender = value;
}
}
All replies (5)
Friday, January 13, 2012 2:09 AM ✅Answered
while (value == 'F' && value == 'M' && value == 'm' && value == 'f')
{...}
chanmm
chanmm
Friday, January 13, 2012 2:28 AM ✅Answered
if (value !='F' && value !='M' && value !='m' && value !='f');
It's a subtle mistake but the semicolon at the end of this line is an unintentional logical error. It turns into an if statement that conditionally executes the empty statement, i.e. nothing. The { ... } block of statements that follow is executed regardless of the condition in the if expression.
Consider this:
if( condition );
{
statement();
}
// The above is equivalent to the following:
if( condition )
{
}
;
{
statement();
}
The { statement(); } block is not part of the if statement, and its contents are executed regardless of the if condition.
It's legal to enclose statements in { }'s without an if, while, do, for, etc.
These are the perils of programming.
Friday, January 13, 2012 5:20 AM ✅Answered
hi
use following code.
private string gender;
public string Gender
{
get
{
return gender;
}
set
{
if (string.Equals(value, "M", StringComparison.InvariantCultureIgnoreCase))
{
gender = value;
}
else if (string.Equals(value, "F", StringComparison.InvariantCultureIgnoreCase))
{
gender = value;
}
else
{
Console.WriteLine("Invalid Gender. Please input again.");
Console.WriteLine("Input Gender: ");
value = Convert.ToString(Console.ReadLine());
Gender = value; //beware of property variable here.
}
}
}
By Country Snail
Friday, January 13, 2012 12:07 AM
Try this:
private char gender;
public char Gender {
get { return gender; }
set {
if(value != 'F' && value != 'M' && value != 'm' && value != 'f') {
Console.WriteLine("Invalid Gender. Please input again.");
Console.WriteLine("Input Gender: ");
Gender = Convert.ToChar(Console.ReadLine());
} else {
gender = value;
}
}
}
I noticed you had a stray ; after your if statement for some reason, but I also added a bit of recursion so that if they type in 'H' at the Input Gender: prompt, it will re-check that H is valid (which it isn't) and reprompt for a valid value. :)
Friday, January 13, 2012 1:03 AM
ohyeah that was a typo too xD i had to type it all over again.
So if i input another letter which isnt "m , M , F , f " it would loop right? Asking to input again another letter :o