Java基礎-執行流程
阿新 • • 發佈:2022-04-04
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
while
和 do 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