x
• Status: Solved
• Priority: Medium
• Security: Public
• Views: 307

# Breaking from a do loop when a condition is not met

I need to continue a do loop until a condition is met:

// Get random Flop1 card
string strImageName = "";
int intCardNumber = 0;
do
{
Random random = new Random();
intCardNumber = random.Next(1, 27);
strImageName = arrCards[intCardNumber, 0] + "Full";

// if condition 1 is true or condition 2 is true, then break out of the loop.
// condition 1 (txtHole1.Text != strImageName)
// condition 2  (txtHole2.Text != strImageName)

if ((txtHole1.Text != strImageName) || (txtHole2.Text != strImageName)) // Make sure that Hole1 or Hole2 and strImageName are not the same
{
break;  // do not get a new random number.
}
} while ((txtHole1.Text != strImageName) || (txtHole2.Text != strImageName));

// Does not break when Condition 1 or Condition 2 is false.

Thanks,
0
Dovberman
• 3
1 Solution

PresidentCommented:
You must think like a computer.

What is OR for you should often be translated to AND for the computer.

What you are doing is to loop as long as one of the conditions is true. So if only one is false, the loop goes on.

What your need to do is to loop as long as both are true. So when one is false, the loop will stop.

Replace || by &&.
0

Author Commented:
if ((txtHole1.Text != strImageName) && (txtHole2.Text != strImageName)) // Make sure that Hole1 or Hole2 and strImageName are not the same
{
break;  // do not get a new random number.
}
} while ((txtHole1.Text != strImageName) && (txtHole2.Text != strImageName));

Yes, this makes sense.  I will try it and give you feedback.

Thanks,
0

Author Commented:
Yes, that works.

Thanks,
0

Author Commented:
Thanks
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.