Java for循環(huán)用于多次迭代程序的一部分,或者多次執(zhí)行同一個代碼塊。如果迭代次數(shù)是固定的,建議使用for循環(huán)。
java中有三種類型的for循環(huán)。如下所示 -
for循環(huán)for-each或增強型for循環(huán)for循環(huán)簡單的for循環(huán)與C/C++相同。我們可以初始化變量,檢查條件和增加/減少變量的值。
語法:
for(initialization;condition;incr/decr){
//code to be executed
}
執(zhí)行流程圖如下所示 -

示例:
public class ForExample {
public static void main(String[] args) {
for(int i=1;i<=10;i++){
System.out.println(i);
}
}
}
執(zhí)行上面的代碼,輸出如下 -
1
2
3
4
5
6
7
8
9
10
for-each循環(huán)用于在java中遍歷數(shù)組或集合。它比簡單的for循環(huán)更容易使用,因為不需要遞增值和使用下標符號。
語法:
for(Type var:array){
//code to be executed
}
示例:
public class ForEachExample {
public static void main(String[] args) {
int arr[] = { 12, 23, 44, 56, 78 };
for (int i : arr) {
System.out.println(i);
}
}
}
執(zhí)行上面的代碼,得到如下結果 -
12
23
44
56
78
我們可以讓每個for循環(huán)的名稱。 為此,在for循環(huán)之前使用標簽。它是有用的,如果在嵌套for循環(huán)中,可以使用break/continue指定循環(huán)。
通常,break和continue關鍵字斷開/繼續(xù)最內(nèi)循環(huán)。
語法:
labelname:
for(initialization;condition;incr/decr){
//code to be executed
}
示例:
public class LabeledForExample {
public static void main(String[] args) {
aa: for (int i = 1; i <= 3; i++) {
bb: for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break aa;
}
System.out.println(i + " " + j);
}
}
}
}
執(zhí)行上面的代碼,得到如下結果 -
1 1
1 2
1 3
2 1
如果使用break bb;它將打斷內(nèi)循環(huán),這是任何循環(huán)的默認行為。
public class LabeledForExample {
public static void main(String[] args) {
aa: for (int i = 1; i <= 3; i++) {
bb: for (int j = 1; j <= 3; j++) {
if (i == 2 && j == 2) {
break bb;
}
System.out.println(i + " " + j);
}
}
}
}
執(zhí)行上面的代碼,得到如下結果 -
1 1
1 2
1 3
2 1
3 1
3 2
3 3
在for循環(huán)中,如果使用兩個分號;,則它對于循環(huán)將是不定式的。
語法:
for(;;){
//code to be executed
}
示例:
public class ForExample {
public static void main(String[] args) {
for (;;) {
System.out.println("infinitive loop");
}
}
}
執(zhí)行上面的代碼,得到如下結果 -
infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c
提示: 在執(zhí)行上面的程序時,您需要按
ctrl + c退出程序。