java - 迭代变量在for循环外是+1?

标签 java arrays

我有一个大小为 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/

相关文章:

java - 将对象从已实现的类添加到数组

java - Java 类可接受的修饰符

java - 具有默认无参数构造函数时出现解码错误 Jaxb - "Class does not have a default no arg constructor"

javascript - 从 .each 循环中的 javascript 数组获取 "undefined"

javascript - JavaScript 中的哈希数组

php - 如果条件没有多个运算符,则使用 stristr 匹配 SINGLE 中数组中的任何值

c++ - 使用 C++ 字符串数组中有多少个字符?

java - Java中如何将值从一个类传递到另一个类?

java - 使用 DrawerLayout,无论哪个屏幕处于 Activity 状态,如何在按“后退”键时关闭应用程序?

java - Keycloak 管理 REST API : Use client root url in e-mail body when performing execute-actions-email