When I try to change the nested for loop the program doesn't work as supposed
This is the original code:
public class AandB
{
public static void main (String [] args) {
int a = 0, b = 2;
int j = 1;
for (int i = 2; i>= 1; i--) {
for(int j = 1; j <=3; j++) {
if(j%2 == 0) {
b = b* 2;
} else {
a= a + b;
}
System.out.println("a=" + a + " b=" + b);
}
}
}
}
It has this output:
a=2 b=2 a=2 b=4 a=6 b=4 a=10 b=4 a=10 b=8 a=18 b=8
I changed this code above so that it could work with a while loop inside the for loop:
public class AandB
{
public static void main (String [] args) {
int a = 0, b = 2;
int j = 1;
for (int i = 2; i>= 1; i--) {
while(j <4) {
if(j%2 == 0) {
b = b* 2;
} else {
a= a + b;
}
System.out.println("a=" + a + " b=" + b);
j++;
}
}
}
}
It has this output:
a=2 b=2 a=2 b=4 a=6 b=4 a=6 b=8
It should output the same results, but I can't get it right. The problem is that after the while loop ends, the for iterates but ignores the while because the condition no longer applies. I suppose I need to clear the variable j? Or create something like a counter variable?