概述

Java中循环有while、do…while…,for,增强for

while

1
2
3
4
5
6
7
8
9
10
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入一个数字:");
int n = sc.nextInt();
int i = 1;
while (i <= n) {
System.out.print(i+" ");
i++;
}
}

do…while…

即使循环条件不满足,也至少执行一次

1
2
3
4
5
6
7
public static void main(String[] args) {
int i = 1;
do {
System.out.print(i + " ");
i++;
} while (i < 6);
}

for

1
2
3
4
5
public static void main(String[] args) {
for (int i = 0; i < 6; i++) {
System.out.print(i + " ");
}
}

增强for

一般用于遍历数组和集合,数据类型为数组或集合的数据类型

1
2
3
4
5
6
public static void main(String[] args) {
int[] intArr = {1, 2, 3, 4, 5};
for (int i : intArr) {
System.out.print(i + " ");
}
}