英文:
Why the array doesn't take the values of previous instructions but only the last?
问题
public class Driver {
static int array[] = {0,0,0,0,0};
public static void main(String[] args) {
for(int i = 0; i < array.length; i ++ ) {
array[i] = 5;
array[i] = 4;
array[i] = 10;
array[i++] = 2;
}
System.out.println(Arrays.toString(array));
}
}
结果:[2,0,2,0,2]
我认为只有最后一个([i++])被考虑了,忽略了前面的值。
英文:
public class Driver {
static int array[] = {0,0,0,0,0};
public static void main(String[] args) {
for(int i = 0; i < array.length; i ++ ) {
array[i] = 5;
array[i] = 4;
array[i] = 10;
array[i++] = 2;
}
System.out.println(Arrays.toString(array));
}
result : [2,0,2,0,2]
I was thinking that only the last one ( [i++] ) is take into account and ignore the previous values
答案1
得分: 1
这有帮助吗?如果我指出你的代码:
for(int i = 0; i < array.length; i ++ ) {
array[i] = 5;
array[i] = 4;
array[i] = 10;
array[i++] = 2;
}
与这个代码是相同的:
for(int i = 0; i < array.length; i+=2 ) {
array[i] = 2;
}
同样的结果;冗余被移除。
英文:
Does it help if I point out that your code:
for(int i = 0; i < array.length; i ++ ) {
array[i] = 5;
array[i] = 4;
array[i] = 10;
array[i++] = 2;
}
Is the same as this:
for(int i = 0; i < array.length; i+=2 ) {
array[i] = 2;
}
Same result; redundancies removed
答案2
得分: -1
为什么数组不会取前面指令的值,而只会取最后一个值?
这是语言设计的方式。实际上,你在同一个变量上进行赋值(array[i] 指向一个内存位置,而你在所有四行中都在为该位置赋值)。因此,预期最后一个赋值会留在那个位置,也就是 2
。
解释代码行为的原因是,
在循环中有两个地方在同一迭代中增加了 i
的值。因此,实际上你在查看 array
中的每隔一个元素。
for(int i = 0; i < array.length; /* 这部分不需要 */ ) {
array[i] = 5;
array[i] = 4;
array[i] = 10;
array[i++] = 2; // 这一行会增加 `i` 的值
}
英文:
Why the array doesn't take the values of previous instructions but only the last?
// hope you are talking about this part,
array[i] = 5;
array[i] = 4;
array[i] = 10;
array[i++] = 2;
This is how the language is designed. You are effectively assigning a value to a same variable (array[i] is pointing to a memory location and you are assigning values for that location in all four lines). So as expected the last one will be the one who remains in that location, which is 2
.
And to explain the behavior of your code,
You have two places where you increment the value of i
in the same iteration in the loop. So effectively you are looking at every other element in the array
for(int i = 0; i < array.length; /* no need this part */ ) {
array[i] = 5;
array[i] = 4;
array[i] = 10;
array[i++] = 2; // this line will increase the value of `i`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论