標有標籤break
只適用於循環。 而且要注意,他們不等效採用goto
因爲他們突破-ED週期後控制轉移到下一條語句。
這裏從language basics tutorial - break statement Oracle的網站上覆制一個例子(我懶得是原創,如果其他很好的例子是可用):
public static void main(String[] args) {
int[][] arrayOfInts = {
{ 32, 87, 3, 589 },
{ 12, 1076, 2000, 8 },
{ 622, 127, 77, 955 }
};
int searchfor = 12;
int i;
int j = 0;
boolean foundIt = false;
search:
for (i = 0; i < arrayOfInts.length; i++) {
for (j = 0; j < arrayOfInts[i].length;j++) {
if (arrayOfInts[i][j] == searchfor) {
foundIt = true;
break search;
}
}
}
if (foundIt) // etc
}
}
萬一你有興趣更多關於如何解決二進制搜索比如何使用break
來標籤。下面的代碼與使用goto的代碼具有相同的性能(如果它們實際存在於java中)。
private static int search(int[] seq, int key, int low, int high) {
while (low <= high) {
// this is as good as low+(high-low)/2.
int mid = (low + high) >>> 1; // this is (low+high)/2
int midVal = seq[mid];
if (midVal < key) {
low = mid + 1;
}
else if (midVal > key) {
high = mid - 1;
}
else {
// why break when you can return?
return mid; // key found
}
}
// key not found. Return the 2's complement of the insert position:
// that is -(insertPosition+1)
return -(low + 1);
}
請將您的問題中的代碼發佈給未來的讀者,以防指向該圖片的鏈接不再有效。 – markspace
郵政編碼不是圖片。舉個例子,我不喜歡導航到由新用戶發佈的隨機Imgur鏈接。 –
@BoristheSpider好吧,我複製它。 –