1. 程式人生 > 其它 >Java基礎-執行流程

Java基礎-執行流程

Java執行流程

這裡指的控制程式執行的語句,比如迴圈語句,終止語句等。

for 迴圈

執行10次迴圈。

for (int i = 0; i < 10; i++) {
    System.out.println(i);
}

執行結果

0
1
2
3
4
5
6
7
8
9

for each 迴圈

遍歷strings陣列。

String[] strings = {"a", "b", "c", "d", "1", "2", "3", "4"};
for (String item : strings) {
    System.out.println(item);
}

while 迴圈

執行10次迴圈。

int i=0;
while (i<10){
    System.out.println(i);
    i++;
}

執行結果

0
1
2
3
4
5
6
7
8
9

do while迴圈

執行10次迴圈。

int i = 0;
do {
    System.out.println(i);
    i++;
}while (i<10);

執行結果

0
1
2
3
4
5
6
7
8
9

whiledo while 稍有不同,while是先判斷條件是否為true,要是true就執行大括號中的內容;而do while是先執行一次大括號中的內容,然後判斷條件是否為true,若為true

,則執行大括號中的內容,否則跳出。

break和continue

break是終止所有迴圈,continue是結束本次迴圈。也就是break是跳出迴圈,continue是本次迴圈之後的不執行,執行下一次的程式。
使用break

for(int i=0; i<10; i++){
    if(i== 5){
        break;
    }else {
        System.out.println(i);
    }
}

這裡用的是break,也就是當i等於5的時候,跳出所有迴圈。

0
1
2
3
4

使用continue

for(int i=0; i<10; i++){
    if(i== 5){
        continue;
    }else {
        System.out.println(i);
    }
}

執行結果中可以看出,知識i等於5的沒有執行,也就是之前說的,跳出本次迴圈,繼續執行下一次。

0
1
2
3
4
6
7
8
9