Java循环结构

  • 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
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值