理解for
循环中的-1
,需要用for
和if
行代码进行详细解释包括在内?
int[] array = { 2, 5, 1, 2, 3, 5 };
Arrays.sort(array);
// why does this start counting from 1, and if l put 0 it goes to error, out of bounds?
for (int i = 1; i < array.length; i++) {
if (array[i] == array[i - 1]) { // - 1?
System.out.print(array[i]);
}
}
最佳答案
它本身并没有什么问题。
它只是使迭代从 i=1
开始,直到数组的长度,但由于数组中的索引是从零开始的,因此在获取值时必须对其进行偏移。
这就是为什么array[i-1]
如果输入i=0
,则还必须将结束条件更改为array.length-1
,并且必须通过访问值array[i]
以避免越界。
关于java - 重复for循环练习,初学者需要建议学习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34345064/