我有一个大小为 4 的数组,我想检查该数组是否包含数字 8(显然不包含,该代码仅用于测试)。
在 for 循环中,j 从 0 变为 3,因此循环中 j 的最终值为 3。但是我不明白为什么循环后 j 的值 after改成4了,怎么还是不是3?
public class Test {
public static void main (String[] args) {
int[] a = new int[4];
a[0] = 2;
a[1] = 3;
a[2] = 4;
a[3] = 5;
int n = a.length; // n = 4
int number = 8;
int j;
for (j = 0; j < n; j++) {
if (a[j] == number) {
System.out.println("The number is at place " + j);
break;
}
// Last value of j is 3:
System.out.println("Value of j after each iteration " + j);
}
// But here j is 4?
System.out.println("Value of j after the for-loop: " + j);
}
}
输出:
Value of j after each iteration 0
Value of j after each iteration 1
Value of j after each iteration 2
Value of j after each iteration 3
Value of j after the for-loop: 4
最佳答案
是的,因为在 for 循环的末尾,变量有一个增量。 for 循环可以重写为:
int j = 0;
while(j < n) {
//code
j++;
}
所以在最后一次迭代时,j
会递增,它会转到条件,并且它会是 false,所以不会进入 for 循环的主体。为了使循环结束,j
必须大于或等于条件。
关于java - 迭代变量在for循环外是+1?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55184381/