Java循环结构知识整理(详细)

一、循环结构

顺序结构的程序语句只能被执行一次。如果想要同样的操作执行多次,,就需要使用循环结构。Java中有三种主要的循环结构,如下:

1.while循环

2.do...while循环

3.for循环

4.JDK5 提供了增强for循环(foreach循环)

二、while循环

语法:

while(布尔表达式){
    //布尔表达式为true时执行的代码块
}

例:

//while循环
@Test
public void test_01(){
    int a = 0;
    while (a <= 5){
        System.out.println("当前a的值为:"+a);
        a++;
    }
}

三、do...while循环

特点:至少执行一次循环体。

语法:

do{
    //布尔表达式为true时执行的代码块,至少执行一次循环
}while(布尔表达式);

例:

//do...while循环
@Test
public void test_02(){
    int a = 0;
    do {
        System.out.println("当前a的值为:"+a);
        a++;
    }while (a <= 5);
}

四、for循环

语法:

for(初始化表达式;布尔表达式:更新控制条件){
    //布尔表达式为true时执行的代码块
}

例:

//for循环
@Test
public void test_03(){
    for(int i = 0; i <= 5; i++){
        System.out.println("当前i的值为:"+i);
    }
}

五、增强for循环

语法:

for(声明语句:表达式){
    //循环体
}

声明语句的数据类型与数组的数据类型一样,表示为当前遍历的元素。表达式为数组的引用,或是返回值为数组的方法。

例:

//增强for循环
@Test
public void test_04(){
    int[] arr = {11,45,12,66};
    for(int i:arr){
        System.out.println("当前数组元素为:"+i);
    }
}

六、死循环

//while死循环
while(为true){

}
//do...while死循环
do{

}while(为true);

//for死循环
for(;;){
    
}

七、break语句

break 主要用在循环语句或者 switch 语句中,用来跳出整个语句块。

例:

//break语句
@Test
public void test_05(){
    int a = 0;
    while (a < 5){
        System.out.println("当前a的值为:"+a);
        if(a == 3){
            break;
        }
        a++;
    }
}

八、continue语句

continue 适用于任何循环控制结构中。作用是让程序立刻跳转到下一次循环的迭代。

在 for 循环中,continue 语句使程序立即跳转到更新语句。

在 while 或者 do…while 循环中,程序立即跳转到布尔表达式的判断语句。

例:

//continue语句
@Test
public  void test_06(){
    int a = 0;
    while (a < 5){
        a++;
        if(a == 3){
            continue;
        }
        System.out.println("当前a的值为:"+a);
    }
}

 

猜你喜欢

转载自blog.csdn.net/u012430402/article/details/81102365