Reputation: 1498
I am running this program to find even numbers in the array, but i do not want my program to check the index 1 of the array. So I did this,
int[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14 };
for (int i = 0; i < numbers.length; i++) {
if ((i != 1)){
if (numbers[i] % 2 == 0) {
System.out.print(numbers[i] + " ");
}
}
}
it gives the correct output,
4 6 8 10 12 14
but if i add other condition to skip both index 1
and 3
,
i.e, if ((i != 1) || (i != 3) )
then if
block is not executed and i get the following output,
2 4 6 8 10 12 14
instead of, 6 8 10 12 14
Why the if
block is not executing the multiple conditions ?
Upvotes: 0
Views: 48
Reputation: 3728
It is working as it is supposed to as the i
variable is either not equal to 1 or not equal to 3 which is true for all numbers. You mean to write i != 1 && i != 3
Upvotes: 0
Reputation: 129507
if ((i != 1) || (i != 3) )
This is always true.
i
is neither 1 nor 3, then both conditions are true.i
is 1, then the right condition is true.i
is 3, then the left condition is true.Perhaps you want
if (!(i == 1 || i == 3))
which is equivalent to
if ((i != 1) && (i != 3))
by De Morgan's Law.
Upvotes: 3