用于Java中的每个循环 [英] For-each Loop in Java
问题描述
我有一个示例代码,它创建了一个大小为10的数组,并尝试在For循环中用反向值初始化它,例如:(9,8,7,6,5 ... 0):
int [] array = new int [10];
for(int i = array.length - 1,j = 0; i> = 0; i--,j ++){
System.out.println(i =的当前值+ i
+当前值j =+ j);
array [j] = i;
System.out.println(Array:+ j +=+ i);
(int k:array){
System.out.println(array [k]);
}
到目前为止,
i = 9的当前值j = 0的现值
数组:0 = 9
i的当前值8 = j的当前值
数组:1 = 8
i的当前值7 = j的当前值
数组:2 = 7
i的当前值6 = j的当前值3
数组:3 = 6
i的当前值5 j的当前值= 4
数组:4 = 5
当前值i = 4当前值j = 5
数组:5 = 4
当前值i = 3当前值= 6
数组:6 = 3
i = 2的当前值j = 7的当前值
数组:7 = 2
i的当前值j = 8的当前值
数组:8 = 1
i的当前值0 = j的当前值9
数组:9 = 0
问题在于For-each循环到底是在数组中打印值:
<$对于(int k:array){
System.out.println(array [k]); pre>
$ / code $ / pre
$ b $ p
当我使用常规的For循环打印数组时,它正常工作。我在这里错过了一些有趣的事情吗?基本上,既然(int k:array) code>导致
k
遍历数组中的值,而不是索引,所做的相当于 p>
System.out.println(array [array [0]]);
System.out.println(array [array [1]]);
System.out.println(array [array [2]]);
System.out.println(array [array [3]]);
...
System.out.println(array [array [9]]);
这不是您想要的。
I have a sample code which creates an "array" of size 10 and tries to initialize it with reverse values in a For loop e.g:(9,8,7,6,5...0):
int[] array = new int[10];
for (int i = array.length - 1, j = 0; i >= 0; i--, j++) {
System.out.println("Present value of i=" + i
+ " Present value of j=" + j);
array[j] = i;
System.out.println("Array:" + j + "=" + i);
}
for (int k : array) {
System.out.println(array[k]);
}
So far so good. This is the output from console which is perfect:
Present value of i=9 Present value of j=0
Array:0=9
Present value of i=8 Present value of j=1
Array:1=8
Present value of i=7 Present value of j=2
Array:2=7
Present value of i=6 Present value of j=3
Array:3=6
Present value of i=5 Present value of j=4
Array:4=5
Present value of i=4 Present value of j=5
Array:5=4
Present value of i=3 Present value of j=6
Array:6=3
Present value of i=2 Present value of j=7
Array:7=2
Present value of i=1 Present value of j=8
Array:8=1
Present value of i=0 Present value of j=9
Array:9=0
The issue is with For-each loop in the end which is just printing the values in array:
for (int k : array) {
System.out.println(array[k]);
}
The values printed array are 0,1,2...9 where it should be 9,8,7...0
When I use the regular For loop to print the array, it works normally. Am I missing some funny business here?
Basically, since (int k : array)
causes k
to go through the values in the array, not the indexes, what you've done is equivalent to
System.out.println(array[array[0]]);
System.out.println(array[array[1]]);
System.out.println(array[array[2]]);
System.out.println(array[array[3]]);
...
System.out.println(array[array[9]]);
which isn't what you want.
这篇关于用于Java中的每个循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!