Looking at the output of this particular method is confusing to me. I’m trying to understand exactly what it’s doing.
This is the method:
for (int i = 0; i < 4; i ++) {
for (int j = 0; j < 9; j++) {
if (j==5) {
break;
}
if ((j==0) || (i==0)) {
continue;
}
if (!((j*i % 3) != 0)) {
System.out.println(j*i);
}
}
}
I know what the output is but I’m still not sure how it’s working, which is why I am asking here. So, This method will go through j until it reaches 5, then it breaks.
Then it increments i, j is 0. J != 5 so it doesn’t break, j == 0 so continue
But then J becomes 3 and I is 1. This is where I’m lost. Where did 3 come from??
I was using this to print out what was going on behind the scenes
public static void tester() {
for (int i = 0; i < 4; i ++) {
for (int j = 0; j < 9; j++) {
if (j==5) {
System.out.println("j == 5, breaking");
break;
}
if ((j==0) || (i==0)) {
System.out.println("J is " + j);
System.out.println("I is " + i);
System.out.println("j or i == 0, continuing");
continue;
}
if (!((j*i % 3) != 0)) {
System.out.println("J is " + j);
System.out.println("I is " + i);
System.out.println(j*i);
}
}
System.out.println();
}
}
And the output is as follows:
J is 0
I is 0
j or i == 0, continuing
J is 1
I is 0
j or i == 0, continuing
J is 2
I is 0
j or i == 0, continuing
J is 3
I is 0
j or i == 0, continuing
J is 4
I is 0
j or i == 0, continuing
j == 5, breaking
J is 0
I is 1
j or i == 0, continuing
J is 3
I is 1
3
j == 5, breaking
J is 0
I is 2
j or i == 0, continuing
J is 3
I is 2
6
j == 5, breaking
J is 0
I is 3
j or i == 0, continuing
J is 1
I is 3
3
J is 2
I is 3
6
J is 3
I is 3
9
J is 4
I is 3
12
j == 5, breaking
The
3(and later on, the6), is occurring from this piece of code…Effectively what
!((j*i % 3) != 0)is saying is, whenj*i/3has a remainder of0, it runs the code within thisifstatement. In other words, it runs thisifcode wheneverj*iis a multiple of3(3,6,9,12)The logic is hard to follow – it’d be better to write it like this…
In the original way, all the
!symbols and multiple brackets/braces make it hard to read.