[英]Why doesn't this break
我下面的代碼來自Oracle。
public class MyLoop {
public static void main(String[] args) {
String[] sa = {"tom ", "jerry "};
for(int x = 0; x < 3; x++) {
for(String s : sa) {
System.out.print(x + " " + s);
if(x == 1) break;
}
}
}
}
輸出:
0 tom 0 jerry 1 tom 2 tom 2 jerry
我正在學習Java,並且遇到了這個問題。 我不明白為什么中斷點為1
時會打印1 tom
。 如果打印了1 tom
,那么為什么沒有1 jerry
?
對於x
每個值,您正在打印表sa
的全部內容,但x == 1除外,其中僅打印sa的第一個值:打印此值后,您要檢查x == 1以及然后離開內部循環並繼續x的下一個值。
首先檢查“ x == 1”,然后打印。
String[] sa = { "tom ", "jerry " };
for (int x = 0; x < 3; x++) {
for (String s : sa) {
if (x == 1) {
break;
}
System.out.print(x + " " + s);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.