"如果程序 (iterations) 从 0 (index) 开始并且我想
循环 12 次,程序输出 4"。
好的,我明白了。您从索引 0 开始计数为文字 1:
1 2 3 4 5 6 7 8 9 10 11 12 (on the 12th iteration starting from Index 0)
-------------------------------------
0 1 2 3 4 5 6 0 1 2 3 4 (element value at index)
-------------------------------------
0 1 2 3 4 5 6 0 1 2 3 4 (array index)
“另一个例子,程序从 index 2 开始并循环 10
次。输出应该是索引 5"。
这个让我很困惑:
1 2 3 4 5 6 7 8 9 10 (on the 10th iteration starting from Index 2)
-----------------------------------
0 1 2 3 4 5 6 0 1 2 3 4 (element value at index)
-----------------------------------
0 1 2 3 4 5 6 0 1 2 3 4 (array index)
输出也应该是索引 4,而不是索引 5。
无论如何,这是可以实现的另一种方法:
int startIndex = 0; // The INDEX value to start iterations from.
int loopNumOfTimes = 12; // The literal number of desired iterations.
int[] array = {0, 1, 2, 3, 4, 5, 6}; // The Integer Array (length 7).
int counter = 0; // A counter used to count literal iterations.
int i; // Decalred outside of loop so its value can be used.
// Iterate through the Array
for (i = startIndex; i < array.length; i++) {
counter++; // Increment counter.
// Have we reached the desire number of iterations?
if (counter == loopNumOfTimes) {
// Yes...Break out of loop.
break;
}
/* Reset the 'for' loop if we've reached actual array length (length minus 1).
i++ in the 'for' loop is automatically applied once the first iteration is
complete and every iteration thereafter as long as 'i' remains less than
the literal length of the array. Because we are applying a value change to
'i' so as to start the loop form 0 again (a loop reset) the i++ will be
immediately be applied which takes 'i' to 1 istead of the desired 0. This
is no good so we set 'i' to -1 that way when i++ is applied 'i' is set to
0 and iterations start again from that index value. */
if (i == (array.length - 1)) {
i = -1;
}
}
// Display the Array element value located at index 'i'.
System.out.println(array[i]);
在上面的代码中,您可以看到起始索引 (startIndex) 为 0 并且保持了所需的循环数(迭代)在 loopNumOfTimes 变量中是 12。控制台窗口的输出将是:4。
如果您将 startIndex 值更改为 2 和 loopNumOfTimes 值到 10 那么控制台窗口输出将为:4。