Speaking from a small program:
1 classLesson6foreach2 {3 Public Static voidMain (string[] args)4 {5 intarray[]={2,3,1,5,4,6};6 7 for(inti=0;i<array.length;i++)//loop output element of array8 {9 System.out.println (Array[i]);Ten } One } A}
View Code
But notice that we don't care about the value of I in the For loop. So since Java5, foreach has come to enhance the For loop.
Format:
for (element type variable: an instance of an array name or iterable)//specific iterable instance the teacher said no tube first, OK, first of all.
{
}
The above program uses the foreach implementation code as follows:
1 classLesson6foreach2 {3 Public Static voidMain (string[] args)4 {5 intarray[]={2,3,1,5,4,6};6 7 for(intX:array)//loop output element of array8 {9 System.out.println (x);Ten } One } A}
View Code
What about encountering a two-dimensional array? Let's take an example of a two-dimensional array:
1 classLesson6foreach2 {3 Public Static voidMain (string[] args)4 {5 Char[] chararray=6 {7{' Send ', ' Meng ', ' Hao ', ' yes ', ' it ', ' Guang ', ' Mausoleum '},8{' So ', ' man ', ' West ', ' resignation ', ' yellow ', ' crane ', ' Lou '},9{' Smoke ', ' Flowers ', ' three ', ' Month ', ' Down ', ' Yang ', ' state '},Ten{' lone ', ' sail ', ' far ', ' shadow ', ' bea ', ' empty ', ' do '}, One{' But ', ' see ', ' Long ', ' River ', ' Day ', ' Inter ', ' flow '} A }; - - for(Char[] x:chararray)//Two-dimensional the { - for(Chary:x) - System.out.print (y); - System.out.println (); + } - } +}
View Code
The results are as follows:
"Java Foundation" foreach Loop