Condition for while loop doesn't work in java - java

I want the loop to repeat if the number is not equal to 0 and rest%2 is equal to 1 or -1. But this does not seem to work:
while (number != 0 && rest%2 == 1 || rest%2 == -1)
How do I have to write the code so it works?

While it's good to learn about operator precedence, your expression can be reduced:
while (number != 0 && rest%2 != 0)
Put another way, n % 2 is 0 for positive and negative even numbers and something not even must be odd (which is what you are testing).

This is the correct way:
while (number != 0 && (rest%2 == 1 || rest%2 == -1))

Have a look at Java operator precedence here https://introcs.cs.princeton.edu/java/11precedence/
If I understand correctly you want to enter the loop in two cases:
number != 0 && rest%2 == 1
OR
rest%2 == -1
If that's true consider using parentheses:
while ((number != 0 && rest%2 == 1) || rest%2 == -1)

Related

Checking to See which of the three conditions in the If Statement was True in Else If, if one was not?

Assumptions: 1 of 3 of the conditions will be 0.
If I have an if statement defined as follows:
if ((condition1 == 0) || condition2 == 0) || condition3 == 0)) {
do something
}
and 3 following else if statements:
else if (condition1 != 0) {
do something
print which of condition 2 or 3 was 0
}
else if (condition2 != 0) {
do something
print which of condition 1 or 3 was 0
}
else if (condition3 != 0) {
do something
print which of condition 1 or 2 was 0
}
I was thinking perhaps putting nested if statements in the first if statement to see which of the three was 0.
Came up with something. What terrible practice it is to be using this many if statements though. (assume memorizeCondition is stored outside the method of ifs)
if (condition1=0 || condition2 = 0 || condition3 = 0)
if(condition1 = 0)
memorizeCondition = condition1;
if(condition2 = 0)
memorizeCondition = condition2;
if(condition3 = 0)
memorizeCondition = condition3;
else if (condition1 != 0)
memorizeCondition;
calculate condition1;
calculate other condition;
else if (condition2 != 0)
memorizeCondition;
calculate condition2;
calculate other condition;
else if (condition3 != 0)
memorizeCondition;
calculate condition2;
calculate other condition;
what about this:
if ((condition1 == 0) || condition2 == 0) || condition3 == 0)) {
do something
} else {
if (condition1 != 0) {
do something
print which of condition 2 or 3 was 0
}
if (condition2 != 0) {
do something
print which of condition 1 or 3 was 0
}
if (condition3 != 0) {
do something
print which of condition 1 or 2 was 0
}
}
If there are a lot more than 3 conditions you can add them to a collection and then use stream.filter() to remove all non matching conditions.

Java difference between || and && in this example

I am making a counter between number ranges and not sure the correct way to do this. I have always used the || operator but reading some examples, I feel I should be using the && command. Here is my example problem...
if(value >= 1 || value <=10){
count1++;
}
else if(value >= 11 || value <= 20){
count2++;
// AND SO ON........
Or should I be using the && operator like
if(value >= 1 && value <= 10){
count1++;
}
else if value >= 11 && value <= 20){
count2++;
}
|| means "or".
&& means "and".
value >= 1 || value <= 10 makes no sense because it's always true. All numbers are 1 or more, or 10 or less. Some numbers are both, but that doesn't matter.
value >= 1 && value <= 10 makes far more sense. There's a limited range of numbers ([1..10]) for which both the first condition and the second condition are true.
|| is the or operator, so the condition value >= 1 || value <=10 is true for all values if you think about it. So, unless you want your counts to be meaningless, use && which is the and operator.

operator precedence && and ||

please ignore the question - its wrong
I am not sure if my question is issue is related to operator precedence- Just to rule out that I added additional bracket. My understanding is in that case that code in each bracket will be executed. So basically all the OR operation will happen and its output would be AND'ed to condition a.
I have below set of parameters a = true and c = 254 , b is not availble ( b is initialized to 0 -At any given time either b or c only is availble) . So for the above condition I am expecting if condition to result in true but it's resulting in false condition. Any reason why ? Also what is best way to debug such things as in where exactly condition is going wrong - any pointers
if ((a == true) && ((b == 460) || (b == 454) || (b == 455) ||
(c> 13568 && c< 14335) ||
(c> 10640 && c< 10655) ||
(c> 11296 && c< 11311) ||
(c> 25600 && c< 26111) || (c== 7825)))
First a is evaluated, if (a == true) evaluated to true, then only it will execute next && statement
((b == 460) || (b == 454) || (b == 455) ||
(c> 13568 && c< 14335) ||
(c> 10640 && c< 10655) ||
(c> 11296 && c< 11311) ||
(c> 25600 && c< 26111) || (c== 7825))
Inside this, it will check for any one condition which is true, and once it encounter any one statement true, it return from there.
For your condition to be true, a must be true, and in addition, at least one of the conditions on b or c must be true.
Therefore, if a==true and c==254, you will get false, since c is not within any of the ranges you allow, and, as you said, b is not available (which I'm assuming means it doesn't have one of the 3 values you allow).
It would be much simpler if the code is written in a more readable manner;
bool isEqualToAny(int valueToCheck, int[] listToCheckIn){
boolean isMatch = false;
(for item in listToCheckIn){
if (item == valueToCheck){
isMatch = true;
break;
}
}
}
bool isWithinRange(int valueToCheck, int min, int max){
return (valueToCheck > min && valueToCheck < max);
}
if ((a == true)
&& (isEqualToAny(b, int[]{460,454,455})
|| isWithinRange(c,3568,14335)
|| isWithinRange(c,10640,10655)
|| isWithinRange(c,11296,11311)
|| isWithinRange(c,25600,26111)
|| isWithinRange(c,10640,10655)
|| (c== 7825)))
In java8 you can use an array of Tuples to make #isWithinRange more like #isEqualToAny

What am i missing in this java code?

if (array[i]<(char)65 || array[i]>(char)122 &&
array[i]>(char)91 || array[i]<=(char)96)
System.out.println("False")
in this code, when i try to assign character 'C' (which is 67 btw) to array[i] it still says false. I did the math and it's not supposed to print "false" as I stated below this line.
(67 < 65 = 0 || 67 > 122 = 0) = 0
(67 > 91 = 0 || 67 <= 96 = 1) = 1
So, this leaves us: 0 & 1 = 0 .
Any ideas?
With some formatting, your code is:
if ( array[i] < (char)65 || array[i] > (char)122 &&
array[i] > (char)91 || array[i] <= (char)96 )
System.out.println("False");
Since && has higher precedence than || (see Operators), this is equivalent to:
if ( array[i] < (char)65
|| ( array[i] > (char)122 && array[i] > (char)91 )
|| array[i] <= (char)96 )
System.out.println("False");
which, since && is short circuiting, is behaviorally equivalent to:
if ( array[i] < (char)65
|| array[i] > (char)122
|| array[i] <= (char)96 )
System.out.println("False");
which, since the last case covers the first, is logically equivalent to:
if ( array[i] > (char)122 || array[i] <= (char)96 )
System.out.println("False");
You'll print False whenever the value it greater than 122 or less than or equal to 96. 67 is less than 96, so you print False. As pointed out the in comments, there is a precedence to the operators. Rather than learning all the details (to predict cases like this), it's easier just to use enough parentheses.
The && is evaluated first, and then the || according to the Java Operator Precedence. So it gets evaluated the following way for 'C'
67>122 && 67>91 //false
67<65 || false //false
false || 67<=96 //true
if you uses parentheses it will solve this problem
if ((array[i]<(char)65 || array[i]>(char)122) &&
(array[i]>(char)91 || array[i]<=(char)96))
I think you may try this by using brackets ():
if ((array[i]<(char)65 || array[i]>(char)122) && (array[i]>(char)91 || array[i]<=(char)96))
System.out.println("False")
Also to note that && has higher precedence

How does Java evaluate this statement?

I have this expression in the if else statement
if (row % 2 == 0 && col % 2 == 0 || row % 2 == 1 && col % 2 == 1) {
return 0;
}
else {
return 1;
}
which behaves as intended, returning 0 when the row and column are either both even or both odd. What perplexes me is how Java didn't read it as
(row % 2 == 0 && (col % 2 == 0 || row % 2 == 1 && col % 2 == 1))
How exactly does Java evaluate a statement without parenthesis?
How exactly does Java read a statement without parenthesis?
By applying the operator precedence rules. The Java language specification says that && has a higher precedence than ||, and that means that:
row % 2 == 0 && col % 2 == 0 || row % 2 == 1 && col % 2 == 1
is equivalent to:
(row % 2 == 0 && col % 2 == 0) || (row % 2 == 1 && col % 2 == 1)
And in fact, == has a higher precedence than &&, so that is equivalent to:
((row % 2 == 0) && (col % 2 == 0)) || ((row % 2 == 1) && (col % 2 == 1))
This page from the Java Tutorial provides more information on operator precedence and how it affects expression evaluation.
For what it is worth, there is a natural parallel between operator precedence in a programming language and the meaning of simple arithmetical expressions ... as you were taught in primary school. For example, you were taught that 1 + 2 x 3 means the same thing as 1 + (2 x 3); i.e. the answer is 7 and not 9. In technical terms, the x (multiplication) operator has higher precedence than the + (addition) operator.
The idea is the same in a typical programming language, except that there is a larger range of operators to deal with ... and the rules are (generally speaking) more precisely specified1.
1 - For instance, since the evaluation of primaries and operators can in some cases have side effects, it can be important to know the precise order in which the sub expressions get evaluated.
That is because of the precedence order. && has precedence over ||.
Look here.

Categories

Resources