最适合网络开发者的网站
Java 编程语言。初学者课程

尿素

Java Arrays Loop


循环遍历数组

You can loop through the array elements with the for loop, and use the length property to specify how many times the loop should run.

The following example outputs all elements in the cars array:

例子

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (int i = 0; i < cars.length; i++) {
  System.out.println(cars[i]);
}
亲自尝试 »

Loop Through an Array with For-Each

There is also a "for-each" loop, which is used exclusively to loop through elements in arrays:

Syntax

for (type variable : arrayname) {
  ...
}

The following example outputs all elements in the cars array, using a "for-each" loop:

例子

String[] cars = {"Volvo", "BMW", "Ford", "Mazda"};
for (String i : cars) {
  System.out.println(i);
}
亲自尝试 »

The example above can be read like this: for each String element (called i - as in index) in cars, print out the value of i.

If you compare the for loop and for-each loop, you will see that the for-each method is easier to write, it does not require a counter (using the length property), and it is more readable.


Test Yourself With Exercises

Exercise:

Loop through the items in the cars array.

String[] cars = {"Volvo", "BMW", "Ford"};
 (String i : ) {
  System.out.println(i);
}