Given the code fragment:



int[] array = {1, 2, 3, 4, 5};

And given the requirements:

Process all the elements of the array in the order of entry.
Process all the elements of the array in the reverse order of entry.
Process alternating elements of the array in the order of entry.

Which two statements are true?

A. Requirements 1, 2, and 3 can be implemented by using the enhanced for loop.
B. Requirements 1, 2, and 3 can be implemented by using the standard for loop.
C. Requirements 2 and 3 CANNOT be implemented by using the standard for loop.
D. Requirement 1 can be implemented by using the enhanced for loop.
E. Requirement 3 CANNOT be implemented by using either the enhanced for loop or the standard for loop.

題解

需求1,按照順序走訪array陣列物件可以使用標準的for loop或是增強的for loop(即foreach)來實作出來。程式如下:

for(int i = 0; i < array.length; ++i){
    int number = array[i];
}
for(int number : array){
}

需求2,反向走訪array陣列物件只可以使用標準的for loop來實作。

for(int i = array.length - 1; i >= 0; --i){
    int number = array[i];
}

需求3,使用標準的for loop,可以間格走訪array陣列物件,實作方式如下:

for(int i = 0; i < array.length; i += 2){
    int number = array[i];
}

所以選項B和選項D的敘述是正確的。