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.
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 的叙述是正确的。
