因爲 break 和 continue 關鍵字不指定“誰”只能控制當前代碼塊
如下雙層for循環,選擇查找到重複數字後,break只能退出一層for循環,導致把整個for都遍歷完
System.out.println(findDuplicate(new int[] {3, 1, 3, 2, 4, 2}));
public static int findDuplicate(int[] nums) {
int result = -1;
int length = nums.length;
for (int x = 0; x < length; x++) {
int num = nums[x];
for (int y = x + 1; y < length; y++) {
if (nums[y] == num) {
result = num;
break;
}
}
}
return result;
}
輸出:
2
應該返回第一個就重複的數字【3】,而遍歷到了最後返回了【2】
更改代碼:爲第一層代碼加上命名標籤
public static int findDuplicate(int[] nums) {
int result = -1;
int length = nums.length;
to:for (int x = 0; x < length; x++) {
int num = nums[x];
for (int y = x + 1; y < length; y++) {
if (nums[y] == num) {
result = num;
break to;
}
}
}
return result;
}
輸出:
3
//標籤命名方式 = name + : 號 ,標籤名可隨意起,但是要遵循Java命名規範
其它代碼塊命名標籤演示
code:{
break code;
}
if1:if (true) {
break if1;
}
for1:for (;;) {
break for1;
}
while1:while (true) {
break while1;
}
do1:do {
break do1;
} while(true);
switch1:switch (0) {
default:
break switch1;
}
//還能起多個標籤名,當然這樣並沒有什麼意義
code0:code1:code2:code3:{
break code0;
//break code1;
//break code2;
//break code3;
}
continue 只能用於循環體
標籤的使用範圍只有在代碼塊裏