Java中有三种主要的循环结构:
- while 循环
public class whileDemo {
public static void main(String[] args) {
int x = 1;
while (x<5){
System.out.println(x);
x++;
}
}
}
while输出结果
1
2
3
4
- do…while 循环
public class doWhileDemo {
public static void main(String[] args) {
int x = 1;
do {
System.out.println(x);
x++;
}while (x<5);
}
}
do…while 结果
1
2
3
4
- for 循环
- public class forDemo {
public static void main(String[] args) {
for (int x =1;x <5; x++){
System.out.println(x);
}
}
}
for 结果
1
2
3
4
do…while 循环和 while 循环相似,不同的是,do…while 循环至少会执行一次。
增强for循环
主要用于数组的增强型 for 循环。
public class forArrDemo {
public static void main(String[] args) {
String [] strList = {"zzzz","xxx","aaa","ccc"};
for (String str:strList){
System.out.println(str);
}
}
}
zzzz
xxx
aaa
ccc