can i ask you if I can have two conditions in one while loop like this?
For example:
I've tried almost everything in my own code.
int a = 0;
bool b = false;
while(a!=5 || b!=true) {
a++;
}
Console.WriteLine("A is successfuly loaded into 5.");
Console.WriteLine("Bool is still " + b);
I expect the output to be 5, but in my program i have an infinite loop.
The variable b is set to false and does not change.
So, the condition of b!=true is always true.
This condition is on the right side of the "or" ( || ) operator.
Hence, the infinite loop results.
This is an infinite loop because of your second condition.
while(a!=5 || b!=true) uses the || (OR) operators which means as long as one of the conditions is true, the whole condition is true
T || F = T ---> True OR False == True
F || T = T ---> False OR True == True
T || T = T ---> True OR True == True
F || F = F ---> False OR False == False
You assigned b = false and then check for b!=true(equivalent to b == false [which is what you assigned it]). This condition is true and because of which it infinitely enters the loop.
Both a!=5 || b!=true have to be false for it to exit the loop.
When designing a check with multiple conditions, the key is to think about how the && and || operations work. Using || will cause the loop to continue until both conditions are false. Using && will cause the loop to continue until either condition is false.
In your case, you've used || so the loop will continue until a=5 AND b=true. Since b will never be true, you've ended up with an infinite loop.
I'm not sure the exact behavior you're looking for, but there are three similar options to write your example loop, depending on how you want the two conditions to behave:
Or
while(a != 5 || b != true) {
a++;
}
The loop will continue if: a != 5 evaluates "true" or b!= true evaluates "true" or both a != 5 and b!= true evaluates "true". The first time both expressions evaluate to "false", the loop will exit.
And
while(a != 5 && b != true) {
a++;
}
The loop will continue if both a != 5 and b!= true evaluates "true". The first time one or both of these expressions evaluates to "false", the loop will exit.
XOR
while((a != 5 && b != true) || (a == 5 && b == true )) {
a++;
}
The loop will continue if both a != 5 and b!= true evaluate "true", or both evaluate "false". The first time exactly one these two expressions evaluates to "false", the loop will exit.
You have an infinite loop because b is always false, and hence, the loop continues since || means OR, and you have implemented it to continue as long as a is not 5 OR b is not true.
Related
It was hard to find a good title explaining the issue. I will try to explain the problem in detail. I try to use a single line if statement with 2 actions inside another if statement. However, this usage fails the parent if statement's result.
Before going into deep I have to stress that the method below returns FALSE:
draggedItem.GetComponent<PreparedItem> ().CheckPreparationAvailability ()
The method above is included inside two if clauses below. Therefore I expect the result FALSE immediately. The only changing part is the last statement, focus there.
Problematic version without parentheseses:
if (acceptedTypeID == draggedItem.CurrentTypeID.foodTypePart1
&& draggedItem.GetComponent<PreparedItem> () != null
&& draggedItem.GetComponent<PreparedItem> ().CheckPreparationAvailability () // RETURNS FALSE, DO NOT FORGET
&& rootTransform.GetComponentsInChildren<DragAndDropItem> ().Length <= 0
&& draggedItem.RootTransform.GetComponentInChildren<PlateCell>()
&& (true)? true : true) { // problem here
'if' is considered as TRUE and the inside is executed ...
}
Working version with parentheseses:
if (acceptedTypeID == draggedItem.CurrentTypeID.foodTypePart1
&& draggedItem.GetComponent<PreparedItem> () != null
&& draggedItem.GetComponent<PreparedItem> ().CheckPreparationAvailability () // RETURNS FALSE, DO NOT FORGET
&& rootTransform.GetComponentsInChildren<DragAndDropItem> ().Length <= 0
&& draggedItem.RootTransform.GetComponentInChildren<PlateCell>()
&& ((true)? true : true)) { // WORKS AS EXPECTED
'if' is considered as FALSE which is expected and the inside is NOT executed ...
}
Consider this:
bool a = true;
bool b = false;
Console.WriteLine(a && b && (true) ? true : true); // Prints true
Console.WriteLine(a && b && ((true) ? true : true)); // Prints false
This happens because the precedence of the ?: operator is such that in the first WriteLine above, it is as if you wrote this:
(a && b && (true)) ? true : true
which is always going to result in true.
The second, of course, is parenthesized so that it works as you expected.
Without the explicit parentheses the statement is executed the same way as if the parentheses would be placed as following, as everything left of the ? is considered as the condition for the inline-if:
if ((acceptedTypeID == draggedItem.CurrentTypeID.foodTypePart1
&& draggedItem.GetComponent<PreparedItem> () != null
&& draggedItem.GetComponent<PreparedItem> ().CheckPreparationAvailability () // RETURNS FALSE, DO NOT FORGET
&& rootTransform.GetComponentsInChildren<DragAndDropItem> ().Length <= 0
&& draggedItem.RootTransform.GetComponentInChildren<PlateCell>()
&& (true)) ? true : true)
So your second example is the valid solution for such a case.
This is my first time using the enumerator interface.
I am Trying to look threw a stack to find next occurrence of a string.
The loop is suppose to loop threw my tags stack and find out if a tag inside my stack is a tag i was looking for. Once the stack gets to the last tag in the stack it crashes and issues the error in the title. The last tag in the list also happens to be the first match for lookforthisTag string variable. I want the while look to exit when the if statement finds a match or when all stack items have been compared.
/*find next opening tag in stack */
int I = 1;
var enumerator = tags.GetEnumerator(); /// create a enumerator variable
/// move to the next tag in stack
while ( enumerator.MoveNext() != false || found == true || I <= countofTags)
{
htmlTags currentTag = enumerator.Current; // this line causes error.
if (currentTag.open_tag == lookforthisTag)
{
found = true;
}
I++;
}///End while.
This line
while ( enumerator.MoveNext() != false || found == true || I <= countofTags)
will execute the following logic
Does the enumerator returns true? If yes enter the loop else check
next condtion
Is found == true? If yes enter the loop, else check the next condition
Is I <= countofTags? If yes enter the loop, else exit the loop
As you can see even when the enumerator return false it enters the loop because at that point found is true, but inside the loop you call enumerator.Current and this triggers the error message.
Probably you want
while ( !found && enumerator.MoveNext() && I <= countofTags)
Consider that a normal foreach loop would do the same
htmlTags found = null;
foreach(htmlTags currentTag in tags)
{
if (currentTag.open_tag == lookforthisTag)
{
found = currentTag;
break;
}
}
if(found != null)
{
// got it...
}
or just using Linq
htmlTags found = tags.FirstOrDefault(x => x.open_tag == lookforthisTag)
if(found != null)
{
// you have found your tag.
}
I want also to mention the fact that your I <= countOfTags logic
doesn't seem to have any utility in the code shown. The variable I will be always equal to the countOfTags (or just simply equal to tags.Count) because you don't break the loop and continue till the end of the enumeration. If you want to know the 'position' of the found tag, just increment it.
I would rewrite your while condition like this:
while ( enumerator.MoveNext() && !found && I < countofTags)
Or just use linq:
tags.Single (currentTag == currentTag.open_tag == lookforthisTag)
The condition in the while will be true even if enumerator.MoveNext() will be false, because of the or conditions.
It can probably be fixed with changing the condition and also using break to get out of the loop.
like this:
while ( enumerator.MoveNext() && I <= countofTags)
{
htmlTags currentTag = enumerator.Current; // this line causes error.
if (currentTag.open_tag == lookforthisTag)
{
found = true;
break;
}
I++;
}///End while.
But, i wouldn't go this way in the first place.
Use LINQ:
var myItem = tags.FirstOrDefault(currentTag=> currentTag.open_tag == lookforthisTag);
My question is why this condition in a for loop makes it cancel out iteration, however it seems to me that condition is fulfilled?! If I try with one of two given variables without using AND operator looping works and continues infinitely.
bool a = false;
bool b = false;
for (; a && b == false; )
{
Console.WriteLine("");
}
This condition
a && b == false
means
a && (b == false)
Since && does short circuit evaluation, the first false will result in false for whole expression, and thus there is no need to evaluate second expression.
Also to add, even with a single & (which doesn't perform short circuit evaluation, your complete condition will result in false.
If you want to compare both a and b to false you can do:
a == false && b == false
or
!a && !b
You should also consider using a while loop, if there is no iteration variable involved.
https://msdn.microsoft.com/en-us/library/aa691323%28v=vs.71%29.aspx
Because the == is evaluated before &&, the condition is a && (b == false)
so false.
Im quite new to C# and am trying to write a super simple loop
while ((var_app_choice != "Exit") || (var_app_choice != "Test"))
{
//stuff
}
I have a console application where an end user will input a value
If this value is not equal (!=) to Exit OR Test then it should loop.
What am i doing wrong here?
Thanks
If you want to come out of the loop, when the User enters Exit or Test then you need the && operator not ||
while ((var_app_choice != "Exit") && (var_app_choice != "Test"))
{
var_app_choice = Console.ReadLine();
//stuff
}
I think you want and not or...
If the value of var_app_choice is "Test", then the first condition is true and the loop will execute. Similarly, if it's "Exit", then the second condition is true. In other words, you have an infinite loop...
Friend,
Consider I am having a data list as
List dataList = new List() { "Apple", "Microsoft", "exit", "Oracle", "Android" };
int i = 0;
while (dataList[i] != "exit" || dataList[i] != "test")
{
Console.WriteLine(dataList[i]);
i++;
}
You would expect that the ouput should be only Apple and Microsoft. When it encounters "exit" in index 2 it should stop.
What really happens(consider it is verifying "exit") is the first condition fails, which means NotEqualTo Operator works fine. The problem is your OR operator. Since "exit" not equals "test", the condition passed and it further enters into the loop.
Your data must not be equal to "exit" and also not equal to "test".
Think you got the problem. For your information, While(condn){} here you can mention any condition that outputs a boolean(true or false).
Thanks and Correct me if I am wrong.
What does result.IsVisible equal?
if(a==b)
result.IsVisible = obj1.status.abc_REPORT == 'Y'
&& obj1.AnotherValue.ToBoolean() == false;
That depends on the values of obj1.status.abc_Report and obj1.AnotherValue.ToBoolean() (and it all depends on whether a==b or not).
I'm not quite sure of what the real question is here - which bit is confusing you?
One bit which may be confusing you is the shortcircuiting && operator (and possibly the lack of bracing!)
The && operator will only evaluate its right hand side if the left hand side evaluates to true: and the overall result of the expression is true if and only if both sides evaluates to true. (I'm assuming no strange user-defined conversions here.)
So another way of writing it would be:
if (a == b)
{
bool visibility = false;
if (obj1.status.abc_REPORT == 'Y')
{
if (obj1.AnotherValue.ToBoolean() == false)
{
visibility = true;
}
}
result.IsVisible = visibility;
}
Note that a condition comparing Booleans, like this:
obj1.AnotherValue.ToBoolean() == false
would usually be written like this:
!obj1.AnotherValue.ToBoolean()
(Note the exclamation mark at the start - the logical "not" operator.)
The same as this, in many less lines:
if (a==b) {
if (obj1.status.abc_REPORT == 'Y') {
if (obj1.AnotherValue.ToBoolean() == false) {
result.IsVisible = true;
}
else {
result.IsVisible = false;
}
}
else {
result.IsVisible = false;
}
}
In simple words:
If a is equal to b:
result will be visible only if:
object1's status's abc_report is Yes(Y = Yes most probably) AND object1's other value cannot be converted to a Boolean
I'm guess result.IsVisible is a boolean
It will be true if the following conditions are true:
obj1.status.abc_REPORT == 'Y'
and
obj1.AnotherValue.ToBoolean() == false
Also, a == b must be true to enter the initial if
lets go line by line:
if(a==b)
obvious if value of a equals value of b the execute following line
result.IsVisible = obj1.status.abc_REPORT == 'Y'
&& obj1.AnotherValue.ToBoolean() == false;
result is some object (maybe winforms controls etc) which has a property IsVisible set it to true if obj1.status.abc_REPORT is equal to 'Y' and also obj1.AnotherValue.ToBoolean() is equal to false;