R
R
RNB2016-03-25 22:57:08
C++ / C#
RNB, 2016-03-25 22:57:08

C# using the || operator - What am I doing wrong?

There is an array with a certain number X. If X is not two or three, execute the branch in if, otherwise - else.
What is the problem: if I leave one check (without or), we only allow "not two" - everything works as it should.
If with || - the if branch is always executed, the else cannot be entered even if X = 2 or 3.
if (arr[1] != 3 || arr[1] != 2)
{
Console.Write("The number is neither two nor three" );
}
else
{
Console.Write("Hit Else");
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Denis Zagaevsky, 2016-03-25
@Realnewbie

You misunderstand the meaning of ||.
You write, literally, "if x is not 2 or x is not 3", which of course is always true.
In this case, && should be used.

A
Alexey Pavlov, 2016-03-25
@lexxpavlov

It is necessary to use AND, not OR, and you get "The number is not two OR not three", that is, it is always true.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question