編寫程序,是先創建一個字符串數組,在使用foreach語句遍歷時,如果發現數組中包含字符串“老鷹”則立刻中斷循環。再創建一個整數類型的二維數組,使用雙層foreach語句循環遍歷,當發現第一個小于60的數組元素,則立刻中斷整個雙層循環,而不是內層循環。
public class Foreach {
public static void main(String[] args){
System.out.println("\n-------------中斷單層循環的例子-------------");
// 創建數組
String[] array = new String[] { "白鷺", "丹頂鶴", "黃鸝", "鸚鵡", "烏鴉", "喜鵲",
"老鷹", "布谷鳥", "老鷹", "灰紋鳥", "老鷹", "百靈鳥" };
System.out.println("在你發現第一只老鷹之前,告訴我都有什么鳥。");
for (String string : array) { // foreach遍歷數組
if (string.equals("老鷹")) // 如果遇到老鷹
break;// 中斷循環
System.out.print("有:" + string+" "); // 否則輸出數組元素
}
System.out.println("\n-------------中斷雙層循環的例子-------------");
// 創建成績數組
int[][] myScores = new int[][] { { 67, 78, 63, 22, 66 }, { 55, 68, 78, 95, 44 }, { 95, 97, 92, 93, 81 } };
System.out.println("寶寶這次考試成績:\n數學\t語文\t英語\t美術\t歷史");
No1: for (int[] is : myScores) { // 遍歷成績表格
for (int i : is) {
System.out.print(i + "\t"); // 輸出成績
if (i < 60) { // 如果中途遇到不及格的,立刻中斷所有輸出
System.out.println("\n等等," + i + "分的是什么?這個為什么不及格?");
break No1;
}
}
System.out.println();
}
}
}
效果如圖所示: