c# do while ( Two condition )
im trying to do a loop when either one of the two conditions are met for ten times..
This involves a box of bottles either Sugar or Salt where the person must pick randomly two bottles. He/She will stop picking when it was choosen 10 times... It doesnt seem to work.
int sugar = 0;
int salt = 0;
do
bottle1.choose
bottle2.choose
{
if ((bottle1 = 'Sugar') && (bottle2 = 'Sugar'))
{
Console.Write("Sugar");
Sugar++;
}
else if (bottle1 = 'Salt') && bottle1 = 'Salt')
{
Salt++;
Console.Write("Salt");
}
else
{
Console.Write("None");
开发者_C百科 }
}
while ((Salt < 10) || Sugar < 10);
Currently you'll keep looping while either of them have been chosen 10 times. I suspect you want:
while (Salt < 10 && Sugar < 10)
Having said that, the code you've given is clearly pseudo-code anyway - it wouldn't compile for various reasons. If you could post a short but complete program demonstrating the problem, we could give an answer with more confidence. Likewise, saying "It doesn't seem to work" is akin to going to the doctor and expecting a diagnosis from "I'm not feeling well." More details please...
You declare salt
and suger
at the start here, but inside the loop you use Salt
and Sugar
. Are they properties you have defined somewhere else? Are you sure they do what you expect them to? Have you tried using the variables inside the loop instead of the properties, so your code looks like this?
int sugar = 0;
int salt = 0;
do
bottle1.choose
bottle2.choose
{
if ((bottle1 = 'Sugar') && (bottle2 = 'Sugar'))
{
Console.Write("Sugar");
sugar++;
}
else if (bottle1 = 'Salt') && bottle1 = 'Salt')
{
salt++;
Console.Write("Salt");
}
else
{
Console.Write("None");
}
}
while ((salt < 10) || sugar < 10);
Your parentheses are uneven on your if
and while
statements, your variable names mismatch, your bottle.choose
statements must also be under the do-while
loop, and you're using an assignment operator =
on your conditions:
int sugar = 0;
int salt = 0;
do {
bottle1.choose();
bottle2.choose();
if ((bottle1 == 'Sugar') && (bottle2 == 'Sugar'))
{
Console.Write("Sugar");
sugar++;
}
else if ((bottle1 == 'Salt') && (bottle1 == 'Salt'))
{
salt++;
Console.Write("Salt");
}
else
{
Console.Write("None");
}
} while ((salt < 10) || (sugar < 10));
I can't tell from your question if you want to stop if EITHER salt or sugar has been chosen, or if you want to stop when 10 total items have been chosen.
If you're looking for the former, then Jon Skeet's answer will do it for you.
If you're looking for the latter, then I think you're looking for the following:
while (Salt + Sugar < 10);
If I understand the code correctly, both bottles must be of the same taste to do the increment.
First error seem to be the test condition for the "Salt", you check twice for the "bottle1", test should be :
else if (bottle1 = 'Salt') && bottle2 = 'Salt')
Your Variables names are mismatching, again you may take the condition for selection of both salt and sugar in the "while statement" itself.
精彩评论