I'm currently studying C# and am currently working on an assignment, everything is going fine as I'm learning as I go along but I'm stuck on one particular thing. The picture I've added shows the message box only appears when the gender is incorrect.

The code I have is:
private void AddEntryButton_Click(object sender, EventArgs e)
{
string p1, p2, p3;
if (GenderTextBox.Text == "Male" || GenderTextBox.Text == "Female" && RaceLengthTextBox.Text == "5K" || RaceLengthTextBox.Text == "10K")
{
NameListBox.Items.Add(NameTextBox.Text);
TimesListBox.Items.Add(String.Format("{0:00:00}", Convert.ToDecimal(TimesTextBox.Text)));
GenderListBox.Items.Add(GenderTextBox.Text);
RaceLengthListBox.Items.Add(RaceLengthTextBox.Text);
}
else if (GenderTextBox.Text != "Male" || GenderTextBox.Text != "Female" && RaceLengthTextBox.Text != "5K" || RaceLengthTextBox.Text != "10K")
{
p1 = "Gender and Race Length";
MessageBox.Show(String.Format("Invalid, please re-enter. : " p1));
}
else
{
p2 = "Gender";
p3 = "Race Length";
MessageBox.Show(String.Format("Invalid, please re-enter. : " p2, p3)); ;
}
}
I feel like I'm truly showing my beginner colours here, so if anyone could give me some advice on how to resolve this I would greatly appreciate it. Also apologies for the Gender Binaryism.
CodePudding user response:
As you are using || and && logical operators wrongly. Try to Separate the conditions like below
if ((GenderTextBox.Text == "Male" || GenderTextBox.Text == "Female") &&
(RaceLengthTextBox.Text == "5K" || RaceLengthTextBox.Text == "10K"))
{
//your code
}
CodePudding user response:
The two conditions around the and && operator are compared together, and not the two groups of ors (||), so your logic is effectively "A" or "B AND C" or "D".
It's best to explicitly combine related conditions in parentheses rather then relying on implicit operator precedence:
if (
(GenderTextBox.Text == "Male" || GenderTextBox.Text == "Female") &&
(RaceLengthTextBox.Text == "5K" || RaceLengthTextBox.Text == "10K")
)
And similarly in the second if as well.
You could also change the logic around and check for each condition separately, combining all of the errors into one message, but that's the simplest change to get what you want.
Your call to String.Format is also incorrect, but that's a separate problem.
