JAVA SE5引入了新的循环写法,即foreach语法。通过一个例子来学习一下:
importjava.util.*; publicclassForEachFloat { publicstaticvoidmain(String[] args) { Randomrand=newRandom(47); floatf[] =newfloat[10]; for(inti=0; i<10; i++) f[i] =rand.nextFloat(); for(floatx : f) System.out.println(x); } }
/* Output:
0.72711575
0.39982635
0.5309454
0.0534122
0.16020656
0.57799757
0.18847865
0.4170137
0.51660204
0.73734957
*///:~
这个例子使用旧的循环写法给数组赋值,用新的foreach写法读取数组的值。形式如下:
for(float x : f) {
}
foreach的写法在很多字符被使用,不如String类取单个字符的写法,以及后续集合类中的Iterable对象。
下面提到了在条件判断和循环语句中使用到的几个中断关键字:return,continue和break。
return关键字之前提到过,有两方面的用途:一方面是指一个函数返回什么值,另一方面它会导致当前方法的退出。例如:
importstaticnet.mindview.util.Print.*; publicclassIfElse2 { staticinttest(inttestval, inttarget) { if(testval>target) return+1; elseif(testval<target) return-1; elsereturn0; // Match } publicstaticvoidmain(String[] args) { print(test(10, 5)); print(test(5, 10)); print(test(5, 5)); } }
/* Output:
1
-1
0
*///:~
在任何循环迭代语句的主体部分,都可以使用break和continue控制循环的流程。其中break是强制退出当前循环,循环不再进行下去;continue是停止当前的迭代执行,跳转到下一次迭代执行。例如:
importstaticnet.mindview.util.Range.*; publicclassBreakAndContinue { publicstaticvoidmain(String[] args) { for(inti=0; i<100; i++) { if(i==74) break; // Out of for loop if(i%9!=0) continue; // Next iteration System.out.print(i+" "); } System.out.println(); // Using foreach: for(inti : range(100)) { if(i==74) break; // Out of for loop if(i%9!=0) continue; // Next iteration System.out.print(i+" "); } System.out.println(); inti=0; // An "infinite loop": while(true) { i++; intj=i*27; if(j==1269) break; // Out of loop if(i%10!=0) continue; // Top of loop System.out.print(i+" "); } } }
/* Output:
0 9 18 27 36 45 54 63 72
0 9 18 27 36 45 54 63 72
10 20 30 40
*///:~
第一个for循环中,i==74的时候,循环break就终止了;i不能被9整除就跳出当前不能被整除的i的循环,执行下次循环,一旦i能被9整除,就执行打印。第二个for循环是foreach的写法,效果和第一个for循环一致。最后一个无穷while循环也是通过break控制循环终止,通过continue控制执行一下次迭代,可以自己琢磨一下。无穷循环的第二种写法是for(;;)。