現在介紹一下在Java中,如果想跳出for循環,一般情況下有兩種方法:break和continue。
break是跳出當前for循環,如下面代碼所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
public class RecTest {
/** * @param args */ public static void main(String[] args) { for(int i=0; i< 10; i++){ if(i==5){ break; } System.out.print(i+" "); } } }
輸出:0 1 2 3 4 |
也就是說,break會跳出(終止)當前循環。continue是跳出當前循環,開始下一循環,如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
public class RecTest {
/** * @param args */ public static void main(String[] args) { for (int i = 0; i < 10; i++) { if (i == 5) { continue; } System.out.print(i+" "); } } }
輸出:0 1 2 3 4 6 7 8 9 |
以上兩種方法沒有辦法跳出多層循環,如果需要從多層循環跳出,則需要使用標簽,定義一個標簽label,然后在需要跳出的地方,用break label就行了,代碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public class RecTest {
/** * @param args */ public static void main(String[] args) {
loop: for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { for (int k = 0; k < 10; k++) { for (int h = 0; h < 10; h++) { if (h == 6) { break loop; } System.out.print(h); } } } } System.out.println("\nI'm here!"); } }
輸出: 012345 I'm here! |
想學習更多關於java的知識,可以點擊小峰在線Java零基礎進行學習。更多java學習課程,可以關注e良師益友。