Java for循環(huán)用于多次迭代程序的一部分,或者多次執(zhí)行同一個(gè)代碼塊。如果迭代次數(shù)是固定的,建議使用for循環(huán)。
java中有三種類型的for循環(huán)。如下所示 -
for循環(huán)for-each或增強(qiáng)型for循環(huán)for循環(huán)簡(jiǎn)單的for循環(huán)與C/C++相同。我們可以初始化變量,檢查條件和增加/減少變量的值。
語(yǔ)法:
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ù)組或集合。它比簡(jiǎn)單的for循環(huán)更容易使用,因?yàn)椴恍枰f增值和使用下標(biāo)符號(hào)。
語(yǔ)法:
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í)行上面的代碼,得到如下結(jié)果 -
12
23
44
56
78
我們可以讓每個(gè)for循環(huán)的名稱。 為此,在for循環(huán)之前使用標(biāo)簽。它是有用的,如果在嵌套for循環(huán)中,可以使用break/continue指定循環(huán)。
通常,break和continue關(guān)鍵字?jǐn)嚅_/繼續(xù)最內(nèi)循環(huán)。
語(yǔ)法:
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í)行上面的代碼,得到如下結(jié)果 -
1 1
1 2
1 3
2 1
如果使用break bb;它將打斷內(nèi)循環(huán),這是任何循環(huán)的默認(rè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í)行上面的代碼,得到如下結(jié)果 -
1 1
1 2
1 3
2 1
3 1
3 2
3 3
在for循環(huán)中,如果使用兩個(gè)分號(hào);,則它對(duì)于循環(huán)將是不定式的。
語(yǔ)法:
for(;;){
//code to be executed
}
示例:
public class ForExample {
public static void main(String[] args) {
for (;;) {
System.out.println("infinitive loop");
}
}
}
執(zhí)行上面的代碼,得到如下結(jié)果 -
infinitive loop
infinitive loop
infinitive loop
infinitive loop
infinitive loop
ctrl+c
提示: 在執(zhí)行上面的程序時(shí),您需要按
ctrl + c退出程序。