用于循环中集合元素的遍历
for(元素变量:元素集合)
{
程序块;
}
解释:如果元素集合中所有元素都被遍历则结束此循环,否则执行程序块。
程序示例:
importjava.util.*;
publicclasssample{
privatevoidprint(){ String[]str={"*************************************","Thesampleshowfourusagesof':'","1.switchsentence","2.?condition","3.continueskipping","4.elementreachinthecollection","*************************************"};for(Stringe:str)System.out.println(e);} publicstaticvoidmain(String[]args){ Randomrand=newRandom(10);intval=0;booleantmp=false;label:for(inti=0;i<10;){ switch(i){ case0:case1:case2:System.out.println("forloop"+i+"");i++;break;default:System.out.println();while(true){ val=rand.nextInt(10);if(val>5?true:false){ i=10;System.out.println();continuelabel;}System.out.println("[continuewhileloop]"+"val="+val);}}}samples=newsample();s.print();}}运行结果:
forloop0
forloop1forloop2[continuewhileloop]val=3
[continuewhileloop]val=0[continuewhileloop]val=3[continuewhileloop]val=0*************************************
Thesampleshowfourusagesof':'1.switchsentence2.?condition3.continueskipping4.elementreachinthecollection*************************************