int i = 3, j = 3;
for (; i++ == j--; i += 2, j -= 2) {
do {
i = i + j;
} while (i % j != 0);
}
System.out.println(i);
System.out.println(j);
我尝试在Eclipse中调试它,结果如下:
由于上一次for循环检查了i和j的值,它们彼此不相等,为什么它从循环中出来?它不是一个无限循环吗?
答案 0 :(得分:1)
它们彼此不相等所以循环终止。如果它们是相等的循环将不会终止这是你的条件。
答案 1 :(得分:1)
for (; ++i != --j; i += 2, j -= 2) {}
条件++i != --j
或i++ != --j
或++i != j--
会导致无限循环。
i ++和j--分别是后递增和递减,所以首先检查条件然后递增值。
答案 2 :(得分:1)
不,它不会遇到无限循环
1. i和j被初始化(i = 3,j = 3)
2.检查条件。并且在检查条件之后值改变(i = 3,j = 2) - > 后增量和后减量
3.内部做while while循环.. i = 4且j保持不变(j = 2)
4. while循环中断的条件。 as(6%2!= 0 ==>返回false)
5.现在for循环的第三部分执行,这使得i = 6且j = 0
6.现在执行条件部分。返回false,然后将i和j的值更改为(i = 9和j = -1)
然后他们将值打印为i = 9和j = -1
如果它是预增量和预减量那么它们将进入无限循环
答案 3 :(得分:1)
您可以将代码更改为while()循环,如下所示: (我分别将i,j替换为m,n)
int m = 3, n = 3;
while( m++ == n-- ){ //Initially m and n are 3
//m becomes 4 due to ++
//n becomes 2 due to --
m = m + n; //m becomes 6
while( m % n != 0){ // 6 % 2 is 0
m = m + n; // Not called
}
m = m + 2; // m becomes 8
n = n - 2; // n becomes 0
//Goes back to the while(m++ == n--) to check condition again.
//However ( 8++ == 0--) is false, so while loop is not called again.
//but, the values of m and n change to 9 and -1 respectively.
}
混合各种类型的循环可能会使调试变得有点复杂。