what does x % 2 > 0 mean in java? - java

I'm currently learning java in my online classes and I'm learning about loops (specifically continue and break statements). The example given to me was:
int j = 0
while (true){
System.out.println();
j++;
System.out.print(j);
if (j%2 > 0) continue
System.out.print(" is divisible by 2");
if (j >= 10) break;
}
I don't understand why its (j%2 > 0) and not (j%2 == 0) because what if 'j' is 5 for example and you do 5%2. Wouldnt the number you get be 1? Or am I missing something? Can someone please explain this to me?
(sorry is I'm not my question is a little confusing. I've never used this site before and I'm pretty young)

Let me explain to you. See the comments next to each line.
int j = 0
while (true){
System.out.println();
j++; //increases the value of j on the next line by 1.
System.out.print(j); //prints 1, the first time because of above, 0 + 1.
if (j%2 > 0) continue //using modulus operator(%) we are doing 1 % 2, answer is 1
//since 1 % 2(if 1 is divisible by 2) > 0 we are
//continue statement breaks the iteration in the
//loop, so anything below this line won't be
//executed.
System.out.print(" is divisible by 2");//this line will only be executed
//if j is divisible by 2. that is
//j is divisible by 2 (j%2 == 0)
if (j >= 10) break; //when j is equal or greater than
//0 we are stopping the while loop.
}

Continue means "go to the top of the loop, skipping the rest of the loop's code" not "continue with the code". So since 5%2 is 1, and 1 > 0, the continue will execute, going directly to the top of the loop and skipping the rest of the body.
Why do they use > 0 instead of != 0? There isn't any technical reason, its a style difference. I personally would have used the latter as its more clear in my mind. But either works.

int j = 0;
while (true){
System.out.println();
j++;
System.out.print(j);
// in this case you won't print any message and you
// are sure that the next number is even (j will be incremented by "continue;").
if (j%2 > 0) continue;
System.out.print(" is divisible by 2");
if (j >= 10) break;
}

X % 2 means the remainder when is x is divided by 2. So if the remainder of x/2 is more than 0, it means that x is an odd number. When x%2 == 0, then x is a positive number

Related

How can I make it so my while-loop only prints even numbers? Java Eclipse IDE

Beginner here. For my coding class, we have an assignment that requires us to print numbers 1-20, but configure it so that it only outputs even numbers. Here is what I have so far but I'm quite stuck. He says to put an if statement and use the "%" operator but I've no idea where to put them.
int counter = 1;
System.out.println("Part 2 - Even Numbers");
while (counter <= 20)
{
//if (counter
System.out.printf("%d ", counter);
counter++;
} // end while loop
Instructions for assignment
My Output
CORRECT Output
if(counter % 2 == 0){
System.out.printf("%d ", counter);
}
counter++;
% operator is mod operator, if counter % 2 == 0 , then counter is an even number
% is an arithmetic operator, it is called MODULO.
Modulo operator returns the remainder of 2 numbers. In this case, we use a modulo to find out whether a number is even or odd.
odd%2 returns 1
even%2 returns 0
The while loop loops through the first 20 elements. So we put an if statement before printing the element. If the counter is an even number i.e (counter%2 == 0) we print that.
This is the code that prints even numbers:
int counter = 0;
System.out.println("Part 2 - Even Numbers");
while (counter <= 20)
{
if (counter%2 == 0){
System.out.printf("%d ", counter);
}
counter++;
} // end while loop
This can also be done without using MODULO operator:
int counter = 0;
System.out.println("Part 2 - Even Numbers");
while (counter <= 20)
{
System.out.printf("%d ", counter);
counter+=2;
} // end while loop
use fori
public static void main(String[] args) {
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0) {
System.out.println(i);
}
}
}
% is the remainder operation

Having trouble understanding why this code does what it does

int x = 0;
boolean b = true;
int[] nums = { 3, 1, 3, 1, 3 };
for (int i = 0; i < nums.length - 1; i++) {
if (nums[i] == 3 && nums[i + 1] == 3)
b = false;
if (nums[i] == 3)
x++;
}
if (nums[nums.length - 2] != 3 && nums[nums.length - 1] == 3)
x++;
System.out.print(x == 3 && b);
In this code, x gets a ++ every time the for loop finds a 3, which gives x a value of 3. by the time the loop is finished. Under the loop however, there is an if statement, that asks if the is a !=3 at -2 and a 3 at |-1, which is a true statement,-2 is 1and-1 is 3, thenx++, which makesx = 4, so why then does it print true in the print statement if it saysx == 3 && bifx == 4`?
What you missed is that the loop doesn't iterate over the last element of the array, so it increments x just twice (since if (nums[i] == 3) is not executed for the last element of the array). Therefore x is 3 at the end (incremented twice by the loop and a third time by the last condition).
for (int i = 0; i < nums.length - 1; i++) // the if (nums[i] == 3) condition is not
// tested on the element whose index is
// nums.length - 1 (and whose value is 3)
// since i doesn't reach nums.length - 1
What happens is the condition is the for loop is: i < nums.length - 1 which means i will have values from 0 (first element) to nums.length - 1 (second last element). As a result, it will only count 2 of the 3s in the array (it will miss out the last one) and thus x will be 2 at this stage.
Finally, the statement:
if (nums[nums.length - 2] != 3 && nums[nums.length - 1] == 3)
x++;
Is satisfied by the array and will thus make x have a value of 3
As a result x == 3 && b is true
It works that way because the loop runs and ends without running over the last index. The statement which is checked is nums[i] == 3 and if it's true, it'll incerement x. However, your code runs only until the index before the last index. Meaning, it'll incerement x only twice.
In the end you increment x to 3.
x does equal 3 the for loop only checks the first 4 elements of the nums array. If you want to to equal to 4, then change the loop to:
for (int i = 0; i < nums.length; i++) {
if (i != nums.length-1 && nums[i] == 3 && nums[i + 1] == 3)
b = false;
if (nums[i] == 3)
x++;
}
Run here
The program iterates the array from index 0 to index (length -1), increasing the value of X for each 3 found.
Since there are not two consecutive 3 in the array, b will remain true.
It will find two 3's, so at the end of the for loop x will be 2.
The if statement will check if the second last (nums.length - 2) is not a 3 (true) and if the last one is a 3 (also true), so x goes up once more to a 3.
Then it prints true because x=3 and b= true

How do you subtract a value from a counter in Java?

Say that length=11 and that I want to subtract 2 from it on every cycle until it reaches 1. Is my code for the for method correct? And what would it be for a while loop?
for(int i =length ; i!=1; i-=2)
EDIT: This was the question. To solve it I made an if statement that if the length%2==1 I would use the for loop listed above. Then I am going to write an else stating modifying the code above to stop at 0. Does this make sense?
The sum of all digits at odd positions (right-to-left starting at 1 as the right-most digit) of a numeric input. (For example, if the input is 432677, the sum would be 7 + 6 + 3 = 16.)
For is not a method. It's a language construct. Just a nitpick.
Almost. If i starts out even you'll never end. Use:
for(int i =length ; i>1; i-=2)
If the 1 is inclusive, you could try:
for(int i = length; i >= 1; i -= 2){ ... }
Or
for(int i = length; i > 0; i -= 2){ ... }
If the 1 is exclusive, you could try:
for(int i = length; i > 1; i -= 2){ ... }

For Loop Doesn't Work Right

Why doesn't this for loop count the right number of times? If I set the variable runs to 3, the loops runs 4 times. (One extra case.)
Thanks in advance!
for (int i = runs; i >= 0; i--)
{
System.out.println("Input Duration of Trip");
Scanner timeCalc = new Scanner(System.in);
System.out.print("Hours ==> ");
int hour = timeCalc.nextInt();
System.out.print("Minutes ==> ");
int minute = timeCalc.nextInt();
System.out.println("You entered: " + hour + " hour(s) and " + minute + " minutes");
System.out.println();
time = convertHoursMinutesToDouble(hour, minute);
totalTime += time;
}
The loop runs for values:
3
2
1
0
That's 4 times.
If you want it to run for values 3, 2 and 1, you can change your for loop to:
for (int i = runs; i > 0; i--)
or
for (int i = runs; i >= 1; i--)
Your mistake is in
i>=0
What the code is doing is going "Ok, i is going to be equal to three. Now, let's see, ok, back up again, subtract one, i =2... subtract one i=1... Now tricky tricky it SKIPS the termination part of the code because it looks at it first BEFORE substracting one so i=0, ok WAIT i=0 so STOP."
Solution?
for (int i = runs; **i >= 1**; i--)
This mistake always messes me up.
Hope the whole "through the mind of the computer thing" doesn't bother you. That's how I tend to think.
Happy coding!
i == 3
i >= 0
println
i--
i == 2
i >= 0
println
i--
i == 1
i >= 0
println
i--
i == 0
i >= 0
println
That was 4 times. You need your condition to be: i > 0
Because you have set greater than or equal to...
So starts at 3 and goes, 2,1,0.

How to check if an integer can be divided by 3

How to check if my integer can be divided by 3 as below:
for(int i=0; i<24; i++){
//here, how to check if "i" can be divided by 3 completely(e.g. 3, 6, 15)?
}
Use the modulo operator.
if(i % 3 == 0)
Also see Modulo operation at Wikipedia
If you are using a loop, you can use the fact that every third number can be divided by 3.
for(int i = 0; i < 24; i += 3) {
System.out.println(i + " can be divided by 3");
System.out.println((i+1) + " cannot be divided by 3");
System.out.println((i+2) + " cannnot be divided by 3");
}
This avoids the need for a modulo and cuts the number of loops by a factor of 3.
Use the MOD operator
for(int i=0; i<24; i++){
if( i%3 == 0 )
// It is divisible by 3
}
Well, what you could do (it might be a bit faster; it is faster on my machine) is:
boolean canBeDevidedBy3 = ((int) (i * 0x55555556L >> 30) & 3) == 0;
instead of
boolean canBeDevidedBy3 = (i % 3) == 0;
However, the multiplication trick only works for -2 <= i <= 1610612735. This answer was inspired by this optimization question. But if I can give you a tip: use (i % 3) == 0. It's so much simpler, and will always work.
Check the remainder of i devided by 3
if (i % 3 == 0) {}
inside the loop:
if (i%3 == 0)
// it can be divided by 3
% is called "mod" or "modulus" and gives you the remainder when dividing two numbers.
These are all true:
6 % 3 == 0
7 % 3 == 1
7 % 4 == 3
if( i % 3 == 0 )
The % operator delivers you the rest of the division i / 3
if( i % 3 == 0 ){
System.out.println("can be divided by 3");
}else{
System.out.println("cant divide by 3");
}
Is this question for real?

Categories

Resources