blah blah blah is here! blah blah » Close

up0down
link

when i only have

if(FirstBandColour == Random1 && SecondBandColour == Random2  )
{
MessageBox.Show ("CORRECT");
}
else if(FirstBandColour != Random1 && SecondBandColour != Random2 )
{
MessageBox.Show ("WRONG");
}



the messagebox come out. but when i type


if(FirstBandColour == Random1 && SecondBandColour == Random2 && bandmultiplyercolour ==bandmultiplyer )
{
MessageBox.Show ("CORRECT");
}
else if(FirstBandColour != Random1 && SecondBandColour != Random2 && bandmultiplayercolour != bandmultiplayer )
{
MessageBox.Show ("WRONG");
}


the messagebox wont come :(

last answered one year ago

3 answers

up1down
link

It's not clear what you're trying to do.

You say that the messagebox comes out with the first bit of code but, in fact, it won't show if FirstBandColour == Random1 and SecondBandColour != Random2 OR if FirstBandColour != Random1 and SecondBandColour == Random2.

There are even more occasions with the second bit of code when the messagebox won't show.

If you want the messagebox to always show then just use 'else' rather than 'else if'.

sry for my poor language :( but can u kindly explain to me wad de different between 'else' and 'else if'?

up0down
link

Suppose 'condition' is a bool expression which is either true or false, then:

if (condition)
{
// do something
}
else
{
// do something else
}

means that, if condition is true, then do something but, if it's false, then do something else.

It's precisely equivalent to:
if (condition)
{
// do something
}
else if (!condition)
{
// do something else
}

There's no need to use 'else if' unless it's a different condition. For example:
if (condition)
{
// do something
}
else if (condition2)
{
// do something else
}

The above code will do nothing unless either condition is true or condition2 is true. If they're both true, then 'do something' will apply.

up1down
link

Just to add to the conversation, for your situation, it would be enough to just use if/else blocks. But to answer why your original code wasn't working, the logic was wrong. Neither condition was true so none of the message boxes would show.

Look up De Morgan's Laws and Negation of a conjunction. Put simply, to negate your first condition (the opposite of correct), you need to use the opposite operation on all operations. i.e., to negate "a == b && c == d" -> "a != b || c != d". The correct logic would be:

if(FirstBandColour == Random1 && SecondBandColour == Random2 )
{
MessageBox.Show ("CORRECT");
}
else if(FirstBandColour != Random1 || SecondBandColour != Random2 )
{
MessageBox.Show ("WRONG");
}

if(FirstBandColour == Random1 && SecondBandColour == Random2 && bandmultiplyercolour == bandmultiplyer )
{
MessageBox.Show ("CORRECT");
}
else if(FirstBandColour != Random1 || SecondBandColour != Random2 || bandmultiplayercolour != bandmultiplayer )
{
MessageBox.Show ("WRONG");
}

Feedback