通过一个可变长度Java数组迭代 [英] Iterating through a variable length Java array
问题描述
我如何遍历一个可变长度的Java数组。
我想我会设置一个while循环,但我将如何检测,我已经达到了数组的结尾。
我想我想是这样的[只需要弄清楚如何重新present myArray.notEndofArray()]
指数= 0;
而(myArray.notEndofArray()){
的System.out.println(myarray的(指数));
指数++;
}
的for(int i = 0; I< array.length,我++)
{
的System.out.println(数组[我]);
}
或
为(字符串值:数组)
{
的System.out.println(值);
}
第二个版本是的for-each循环,并将其与阵列和收藏的作品。多数循环也可以在for-each循环来完成,因为你可能不关心实际的指数。如果你做一下实际的指标我们的第一个版本的照顾。
只是为了保持完整性你可以做while循环是这样的:
指数= 0;而(指数< myArray.length)
{
的System.out.println(myarray的[指数]);
指数++;
}
但是,你应该使用一个for循环,而不是一个while循环,当你知道的大小(甚至与你知道的大小可变长度数组......这只是每次都不同)。
How do I iterate over a Java array of variable length.
I guess I would setup a while loop, but how would I detect that I have reached the end of the array.
I guess I want something like this [just need to figure out how to represent myArray.notEndofArray()]
index = 0;
while(myArray.notEndofArray()){
system.out.println(myArray(index));
index++;
}
for(int i = 0; i < array.length; i++)
{
System.out.println(array[i]);
}
or
for(String value : array)
{
System.out.println(value);
}
The second version is a "for-each" loop and it works with arrays and Collections. Most loops can be done with the for-each loop because you probably don't care about the actual index. If you do care about the actual index us the first version.
Just for completeness you can do the while loop this way:
index = 0;
while(index < myArray.length)
{
system.out.println(myArray[index]);
index++;
}
But you should use a for loop instead of a while loop when you know the size (and even with a variable length array you know the size... it is just different each time).
这篇关于通过一个可变长度Java数组迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!