checking multiple conditions in an if else block - c#

This seems like it should be simple, but this block of code is not working.
I just need to check and make sure the current race_position is not equal to the total count or not greater than the count or not equal to 0. If it's any of those, then I want to break out of the loop.
I even went through it in the visual studio debugger, and saw when race_position was 0, it still acted as if it was not 0 and never broke out of the loop.
Is there a way to simply this and make it work?
Thanks!
if (race_position != race_team.Count || !(race_position > events.Count) || race_position != 0)
{
next_position = (race_position + 1);
}
else
{
break;
}

you are ORing (||) the conditions together, meaning if one is true, then that block will execute. You want to AND (&&) them together, so that they all must be true, or else the loop will exit.
when race_position is 0, then race_position != race_team.Count is true, hence your loop continues.

if(!(race_position < race_team.Count && race_position > 0))
break;
next_position = (race_position + 1);

Related

While loop not properly checking all conditions?

So the assignment is as follows: you can enter all sorts of numbers but when you enter 0 two times in a row it needs to stop. The first time you enter a number your not allowed to enter 0.
This is the code I have setup:
class MainClass
{
public static void Main (string[] args)
{
int givenNumber, prevNumber;
Console.WriteLine ("Enter a number: ");
int.TryParse (Console.ReadLine (), out givenNumber);
// I've set the prevNumber to givenNumber because the variable has to be initialized
// before I can use it in the condition below. I thought setting it to the giveNumber
// wouldn't harm. Note that the first time your not allowed to enter 0
prevNumber = givenNumber;
while (givenNumber != 0 && prevNumber != 0) {
prevNumber = givenNumber; //Here is where they both are 0 at a given moment, but only after the condition.
Console.WriteLine ("Enter a number: ");
int.TryParse (Console.ReadLine (), out givenNumber);
}
Console.WriteLine ("Tada");
}
}
The problem is that it already stops when you've only entered one 0. For example if I'd first enter a 7 to start with, and my next number would be 0. When I debug it it says that my givenNumber is 0 and prevNumber is 7, when it goes back to the while condition it stops and finishes. When the program finishes the debug clearly says prevNumber = 7 and givenNumber = 0. I am using the conditional AND correct am I not?
Any clue? I'm not allowed to use arrays for this matter.
Thanks in advance
Ooh, right, you've got the logic wrong. It should be this:
while ((givenNumber != 0) || (prevNumber != 0)) {
Look up DeMorgan's laws to see why...
Your problem is with your conditional statement.
Right now you're checking whether both the givenNumber and the PrevNumber DO NOT equal 0.
So, if neither of them equals 0 then the statement will evaluate to TRUE. However, if either one of the numbers is 0 then the statement will evaluate to FALSE, since (TRUE) && (FALSE) evaluates to FALSE.
There are two ways to fix this: You can either use || (the "OR" operator) with the two "!=" statements, or you can negate the whole thing and use regular equality rather than "!=" as such: !(givenNumber == 0 && prevNumber == 0)
while (givenNumber != 0 && prevNumber != 0)
For first read value from console - number 7
givenNumer will be 7
prevNumber will be 7 too (because of assignment prevNumber = givenNumber;)
Thus while (7 != 0 && 7 != 0) will pass
Second read from Console - number 0
Thus while (0 != 0 && 7 != 0) will not pass because 0 != 0 is FALSE and while loop ends if condition is result is FALSE

Or in IF statement not working properly

I have this Or condition in an IF statement (in a foreach loop) in a Windows Form C# program:
if ((splittedFile.Count() != 3) || (splittedFile.Count() != 4))
continue;
and it always does continue, even if splittedFile.Count() is 3 or 4.
The thing is that if I remove the Or condition:
if ((splittedFile.Count() != 4))
continue;
it works properly!! Any ideas why?
This is the correct behavior, you need to use &&.
The reason is that the count is fixed number, let's say n. Now the condition reads:
n is not 3 or n is not 4.
Given n is 4, this means it is not 3, thus the test succeeds and vice versa.
A compiler can't detect this is trivially true, because between the two if statements, the Count() might change (for instance in a multithreading setting where the second thread would add/remove something to/from the collection). I agree however some analysis tools could be capable in some conditions to detect such trivial behavior. In general however such analysis can't be implemented because of Rice's theorem.
If you use &&, the expression reads:
n is not 3 and n is not 4.
Thus both conditions should be true. In other words only if n is less than three and greater than 4, the condition holds.
Try:
if ((splittedFile.Count() != 3) && (splittedFile.Count() != 4))
continue;
I know || sound logical because : if splittedFile.count is not 3 OR it is not 4 then continue; But because there are 2 NOT ! operators in the if expression an AND && is needed.
put a real number into your expression:
if( 3 != 3 || 3 != 4)
which is
if( false || true )
your expression will always be true, as splittedFile.Count() is always (not 3) or (not 4)
you want to && your results together, which looks like
(x != 3) || (x != 4)
or
!( x == 3 || x == 4)
Because one of your expressions will be always true. That's why true || something always returns true.
Let's analyze your splittedFile.Count() is 3, 4 and other than these values.
For 3, your expression will be false || true and this returns true.
For 4, your expression will be true || false and this returns true.
For other than 3 or 4, your expression will be true || true and this returns true.
Strongly suspect you are looking for && operator which provides logical-AND.

Why does while loop OR not work but AND does?

I have a simple while loop in C# and basically I'm testing two conditions
while (opponentOne.HP >= 0 || opponentTwo.HP >= 0)
Which when I read this means, while the first opponents HP is more than equal to 0 OR the seconds opponents HP is more than equal to 0, exit. So when only one of them are true, exit the while loop?
However this does not do what I want it to do, it waits for both of them to become true before exiting the loop, however if I change || to && it will work
while (opponentOne.HP >= 0 && opponentTwo.HP >= 0)
Which now says while the firsts opponents HP is more than 0 and the seconds opponent is more than 0, exit...
Have I got something mixed up here?
I thought the loop should break when both conditions are met.
The condition isn't the condition "to exit", it's the condition to continue
So first one says "continue looping as long as either oponents have >0HP" and the second one says "continue as long as both opponents have >0HP"
A while loop will keep looping until the condition BECOMES FALSE.
So in the first case :
NOT (1.HP >= 0 || 2.HP >= 0)
if we apply DeMorgan's equivalency to it:
It will break when
NOT 1.HP >= 0 AND NOT 2.HP >= 0
Have I got something mixed up here?
Yes, && means that both sides must be true(both oppponents must be alive), otherwise the loop is exited.
|| means that one of both sides must be true, so only one opponent must be alive.
Replace the while-loop with an if-statement(for demonstration purposes only):
if(opponentOne.lives && opponentTwo.lives)
{
// do something
}
else // one is dead
{
// exit
}

building a FOR loop with several IF's and causing it to stop only in some runs

I have a 2D array which some of it's members are numbers (playerID -1,2,3,4 etc.)and the rest are zeros.
I want to make a for loop containing all kinds of check methods that goes through the the loop and returns an answer. the checks are ranked, so that when one of the higher checks is returned TRUE, the loop for that playerID can terminate. Later on I want to use the check results to compare between the players, but first thing's first - I can't get the big FOR loop running.
I had in mind something like this:
for (int playerID = 1; playerID <= participants; playerID++)
{
checkA = Check4forsequenceof4(matrix); //method A
if (checkA == 0)
continue;
else
Console.WriteLine(p + "completed check A");
break;
if (checkB == 0)
continue;
else
Console.WriteLine(p + "completed check B");
break;
if (checkC == 0)
continue;
else
Console.WriteLine(p + "completed check C");
break;
}
Problems are: the break breaks out of the FOR loop instead of only from the if, and I can't think of how to check for the next playerID, and also can't figure out how best to store the results for every player for later display.
First off, if you want to make this work, you can't rely on indentation - you need braces:
if (checkA == 0)
continue;
else
{
Console.WriteLine(p + "completed check A");
break;
}
This will solve your immediate problem of the loop immediately breaking out.
That being said, given the above check, you'll NEVER check for B. I suspect you want to invert your logic, as such:
if (checkA != 0)
{
Console.WriteLine(p + "completed check A");
break;
}
This will cause checkA to run, then checkB, etc.
You have a much bigger problem. Your code reads:
checkA = Check4forsequenceof4(matrix); //method A
if (checkA == 0)
continue;
else
Console.WriteLine(p + "completed check A");
break;
That will always break out of the loop the first time checkA is not 0. So checkB will never be executed.
I'm not sure what you're trying to do. The indentation of your code indicates that the break isn't necessary anywhere, since the default is tao fall through (which I think is what you want to do).
var allPlayers = new List<Player>();
// Fill the list allPlayers here.
var validPlayers = new List<Player>();
foreach (Player p in allPlayers) {
if(CheckA(p) || CheckB(p) || CheckC(p)) {
validPlayers.Add(p);
}
}
Note: c# performs a so called shortcircuit evaluation. I.e. if CheckA returns true the others will not be evaluated any more. If CheckB returns true, then CheckC will not be evaluated. By the way "||" is a logical OR. If all checks have to be OK then use the logical AND "&&" instead. Here c# will stop checking as soon as a check fails.
If you are only interested in which check has returned true first, then only use "continue" when the check is OK, but no "break" otherwise.
My answer might not be very appropriate, but I am not really sure what you are trying to do.
I think this is what you're looking for. Though I don't know when checkB or C is supposed to be set. After the checkA check?
for (int playerID = 1; playerID <= participants; playerID++)
{
checkA = Check4forsequenceof4(matrix); //method A
if (checkA == 0)
continue;
Console.WriteLine(p + "completed check A");
if (checkB == 0)
continue;
Console.WriteLine(p + "completed check B");
if (checkC == 0)
continue;
Console.WriteLine(p + "completed check C");
}
unless I misunderstand your question:
for (int playerID = 1; playerID <= participants; playerID++)
{
checkA = Check4forsequenceof4(matrix); //method A
if (checkA != 0)
Console.WriteLine(p + "completed check A");
else
continue;
if (checkB != 0)
Console.WriteLine(p + "completed check B");
else
continue;
if (checkC != 0)
Console.WriteLine(p + "completed check C");
else
continue;
}
Restructure your if statements...
if (0 != checkValue) {
Console.WriteLine(p + " completed check X");
Continue;
}
So this will cause the loop to go into the next iteration when a check value is non-zero.
There is no such thing as breaking out of an if statement.
I came up with the following code.
// This store all of the checks formed as Fun<Player, bool> delegates.
var checks = new List<Func<Player, bool>>();
checks.Add(x => DoesPlayerSatisfyCheck1(x));
checks.Add(x => DoesPlayerSatisfyCheck2(x));
checks.Add(x => DoesPlayerSatisfyCheck3(x));
// Add more checks here if necessary.
// This stores all players who have passed a check.
// The first check that passed will be associated with that player.
var results = new Dictionary<Player, int>();
// Loop through all players.
foreach (Player p in participants)
{
// Now perform each test in order.
for (int i = 0; i < checks.Count; i++)
{
Func<Player, bool> checker = checks[i];
if (checker(p))
{
results.Add(p, i);
break;
}
}
}
After this code executes the results data structure will contain an entry for each Player that passed one of the checks. That entry will also contain the check number. If you want to add more checks later you can simply add it to the checks data structure.
This code does not behave the same as what you posted. But, it does behave per the requirement you gave; as best I can tell anyway.

if else condition in windows phone 7

I am trying to do something like a if else condition in C#.
My below code is to check that all the text in text block is correct and show a display message.
if ((correctAns.Contains(textBlock1.Text)) &&
(correctAns.Contains(textBlock2.Text)) &&
(correctAns.Contains(textBlock3.Text)) &&
(correctAns.Contains(textBlock4.Text)) &&
(correctAns.Contains(textBlock5.Text)))
{
//If it contains the correct answer
MessageBox.Show("All correct");
}
What i want for now is to check if any 3 of the text in the text block is correct will show a message box.
How should i go about doing it?
It might be easier to put all the textboxes in an array and use Linq to count:
if (textboxes.Where(tb => correctAns.Contains(tb.Text)).Count() >= 3)
{
// show message
}
This way it is much easier to add or remove textboxes to this check.
Count them.
If your code matches the entire problem, this is probably the most straight-forward - but if the number of text blocks grow, you might want to re-think the solution:
int count = 0;
if (correctAns.Contains(textBlock1.Text)) count++;
if (correctAns.Contains(textBlock2.Text)) count++;
if (correctAns.Contains(textBlock3.Text)) count++;
if (correctAns.Contains(textBlock4.Text)) count++;
if (correctAns.Contains(textBlock5.Text)) count++;
if (count >= 3)
{
MessageBox.Show("At least 3 correct");
}
If you want any three in any combination, writing out a single conditional block to cover everything will be pretty rigid and non-flexible. It will be better to count them, then check the count.
int count = 0;
if (correctAns.Contains(textBlock1.Text))
++count;
if (correctAns.Contains(textBlock2.Text))
++count;
if (correctAns.Contains(textBlock3.Text))
++count;
if (correctAns.Contains(textBlock4.Text))
++count;
if (correctAns.Contains(textBlock5.Text))
++count;
if (count >= 3) {
// Show message.
}

Categories