-
while
-
do while
-
for循环
-
Java增强for循环
-
break关键字
-
continue关键字
while
结构:
while(布尔表达式){ //循环内容 }
例子:
public class Loop { public static void main(String[] args) { int a = 1; while(a < 5){ System.out.println("a=" + a); a++; } } }
运行结果:
a=1 a=2 a=3 a=4 Process finished with exit code 0
do while
do while循环语句和while类似,不同的是do while把循环条件放在了循环体的后面,意思就是无论循环条件是否成立,循环体都会无条件执行一次。
结构:
do{ //循环体 }while(循环条件);
例子:
public class Loop { public static void main(String[] args) { int a = 1; do { System.out.println("a=" + a); a++; }while (a < 5); } }
运行结果:
a=1 a=2 a=3 a=4 Process finished with exit code 0
for循环
结构:
for(初始化;布尔表达式;更新){ //代码语句; }
java增强for循环
主要用于数组的增强型for循环,结构:
for(声明语句:表达式){ } //声明语句:声明新的局部变量,类型与数组里的值类型一致; //表达式:是要访问的数组名,或者是返回值为数组的方法。
例子:
public class Loop { public static void main(String[] args) { String[] names = {"jenny","lily","lucy"}; for(String name:names){ System.out.println(name); } } }
运行结果
jenny lily lucy Process finished with exit code 0
break
当break语句出现在循环语句中,作用是跳出循环语句,执行后面的代码;
当break语句出现在switch条件语句中,作用是终止某个case并向下执行。
结构:
break;
例子:
public class Loop { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40}; for(int number: numbers){ if(number == 40){ break; } System.out.println(number); } } }
运行结果:
10 20 30 Process finished with exit code 0
continue
continue适合任何循环控制结构中。作用是让程序立刻跳转到下一次循环的迭代。
for循环中,continue语句立即跳转到更新语句;
while、do while循环中,continue语句立即跳转到布尔表达式的判断语句。
结构:
continue;
例子:
public class Loop { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40}; for(int number: numbers){ if(number == 20){ continue; } System.out.println(number); } } }
运行结果:
10 30 40 Process finished with exit code 0
Java循环结构
最新推荐文章于 2024-09-14 21:48:00 发布