为什么满足这个条件? (j == nElems)

时间:2017-02-28 23:44:38

标签: java arrays

我写了这段代码来找到一个工作得很好的数组中的元素,但我不明白它是如何工作的100%。我的问题是,当它从0到9时,怎么来(j == nElems)?我还注意到,当找不到搜索关键字时,在for循环之外满足条件。

public class ArrayApp {
    public static void main(String args[]) {
        int nElems = 10;
        int[] arr = new int[nElems];
        int j;
        int searchKey;
        arr[0] = 77;
        arr[1] = 99;
        arr[2] = 44;
        arr[3] = 55;
        arr[4] = 22;
        arr[5] = 88;
        arr[6] = 11;
        arr[7] = 00;
        arr[8] = 66;
        arr[9] = 33;
        for (j = 0; j < nElems; j++) {
            System.out.print(arr[j] + " ");
        }
        System.out.println();
        //Find 66 in array
        searchKey = 66;
        for (j = 0; j < nElems; j++) {
            if (arr[j] == searchKey) {
                break;
            }
        }
        if (j == nElems) {
            System.out.println("Cant find " + searchKey);
        } else {
            System.out.println("Found " + searchKey + " in position " + j);
        }
        //Remove 55 from array
        searchKey = 55; // delete item with key 55
        for (j = 0; j < nElems; j++) { // look for it
            if (arr[j] == searchKey) {
                break;
            }
        }
        for (int k = j; k < nElems - 1; k++) { // move higher ones down
            arr[k] = arr[k + 1];
        }
        nElems--;
        for (j = 0; j < nElems; j++) {
            System.out.print(arr[j] + " ");
        }
    }
}

4 个答案:

答案 0 :(得分:1)

让我们看一下你的for循环:

for (j = 0; j < nElems; j++) {
    if (arr[j] == searchKey) {
        break;
    }
}

Here Oracle的文档中有关for循环的内容:

  

每次迭代后都会调用increment表达式   环;这个表达式增量或完全可以接受   递减一个值。

因此,在上面的循环中,j在每次迭代后递增。在倒数第二次迭代中,j将为nElems-1。它将执行循环并递增j,然后使其等于nElems

当循环之后放置if条件时,到时间控件到达它时,j已经等于nElems,因此它将是true

答案 1 :(得分:1)

我们可以尝试简化for循环的含义

for (j = 0; j < nElems; j++) {
    if (arr[j] == searchKey) {
        break;
    }
}

for循环基本上分解为:

int j = 0;
int nElems = 10;
while(j < nElems) {
    if(arr[j] == searchKey) {
        break;
    }
    j++;
}

你可以看到最终条件是j等于10(nElems)。

答案 2 :(得分:0)

在每次迭代结束时,j会递增。之后,测试停止条件。如果该条件为真,则循环退出。否则,它将继续使用新值j

这意味着您的for循环的运行时间与j < nElems一样长。 j == nElems for后,j循环完成。因此,最后nElems必须等于{{1}};否则循环永远不会终止。

答案 3 :(得分:0)

for (j = 0; j < nElems; j++) {
    if (arr[j] == searchKey) {
        break;
    }
}

nElems是10.所以j&lt; nElems将满足,直到j达到10.此时,它将退出循环。但是,如果

,它只会达到这一点
arr[j] == searchKey
永远不会满足

(即找不到搜索关键字)。所以你所看到的是从未找到搜索关键字,j递增到10,此时循环退出。此时,j == nElems。

相关问题