Java 循环结构
Posted 我是痕
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java 循环结构相关的知识,希望对你有一定的参考价值。
for 循环
for循环执行的次数是在执行前就确定的。
说明:
- 最先执行初始化步骤。可以声明一种类型,但可初始化一个或多个循环控制变量,也可以是空语句。
- 然后,检测布尔表达式的值。如果为 true,循环体被执行。如果为false,循环终止,开始执行循环体后面的语句。
- 执行一次循环后,更新循环控制变量。
- 再次检测布尔表达式。循环执行上面的过程。
/*格式
for(初始化; 布尔表达式; 更新) {
//代码语句
}
*/
public class Test {
public static void main(String args[]) {
for(int x = 0; x < 5; x++) {
System.out.println("value of x : " + x );
}
}
}
运行结果:
value of x : 0
value of x : 1
value of x : 2
value of x : 3
value of x : 4
while 循环
- 只要布尔表达式为 true,循环就会一直执行下去
/*格式
while(布尔表达式){
//循环内容
}
*/
public class Test {
public static void main(String args[]) {
int x = 0;
while( x < 5 ) {
System.out.println("value of x : " + x );
x++;
}
}
}
运行结果:
value of x : 0
value of x : 1
value of x : 2
value of x : 3
value of x : 4
无限循环的最简单表现形式
for(;;){}
while(true){}
do while 循环
- 即使不满足条件,也至少执行一次
/*格式
do{
//代码语句
}while(布尔表达式);
*/
public class Test {
public static void main(String args[]){
int x = 0;
do{
System.out.println("value of x : " + x );
x++;
}while( x < 5 );
}
}
运行结果:
value of x : 0
value of x : 1
value of x : 2
value of x : 3
value of x : 4
break 关键字
主要用于循环语句或者 switch 语句中,用来跳出整个语句块。
/*格式
break;//加入这句语句
*/
public class Test {
public static void main(String args[]){
for(int x = 0; x < 10; x++){
if( x == 5 ){
break;
}
else{}
System.out.println("value of x : " + x);
}
}
}
运行结果:
value of x : 0
value of x : 1
value of x : 2
value of x : 3
value of x : 4
continue 关键字
主要用于让程序立刻跳转到下一次循环的迭代。
- 在 for 循环中,continue 语句使程序立即跳转到更新语句。
- 在 while 或者 do…while 循环中,程序立即跳转到布尔表达式的判断语句
public class Test {
public static void main(String args[]){
for(int x = 0; x < 5; x++){
if( x == 2 ){
continue;
}
else{}
System.out.println("value of x : " + x);
}
}
}
运行结果:
value of x : 0
value of x : 1
value of x : 3
value of x : 4
以上是关于Java 循环结构的主要内容,如果未能解决你的问题,请参考以下文章