[1]Java基础一遍过---【循环结构,增强for ,break ,continue 详解】5分钟掌握

首先,我们需要知道为什么要用到循环?

比如我们需要 同样的操作 执行 多次

Java中三种主要循环结构:

while 循环
do_while 循环
for 循环
以及在 Java5 中引入了一种 主要用于 数组增强型 for 循环

循环结构的四个要素:

初始化条件
循环条件
循环体
迭代条件

一、while 循环

while循环的基本结构:


//初始化条件
while( 循环条件 ) { 
 //循环体
 //迭代条件
}
//只要循环条件为true,便会一直循环

代码实例:


public class test {
    public static void main(String[] args) {
        int x = 1;
        while( x < 10 ) {
            System.out.println("关注,点赞,收藏");
            x++;
        }
    }
}

二、do_while 循环

该循环与while循环相似,不同的是会先执行一次代码,再去判断表达式是否为true


//初始化条件
do { 
 //循环体
 //迭代条件
}while( 循环条件 );

代码示例:


public class test {
    public static void main(String[] args) {
        int x = 1;
        do {
            System.out.println("关注,点赞,收藏");
            x++;
        }while (x < 1);
    }
}

三、for 循环

for循环是最常用的一种循环结构,简单方便


for(初始化条件;循环条件;迭代条件){
    循环体
}

代码示例:


public class test {
    public static void main(String[] args) {
        for (int i = 1; i <5; i++) {
            System.out.println("关注,点赞,收藏");
        }
    }
}

四、增强for循环

增强for循环主要用于数组,但是初始化条件的变量类型且需要与数组内元素的类型匹配。


for(声明一个新的局部变量:数组名){

}

代码实例:


public class test {
    public static void main(String[] args) {
        int [] str = {”关注“,”点赞“,"收藏"};
        for(String a : sz){
            System.out.println(a+",");
        }
    }
}

五、break ,continue关键字

break用法:用于跳出循环结构


for (int i = 1; i <5; i++) {
    if( i==3 ) {
        System.out.println("关注,点赞,收藏");
        break;//跳出循环
    }
}

continue用法:

continue 适用任何循环结构。其作用是让程序立刻跳转到下一次迭代条件。


for (int i = 1; i <=5; i++) {
    if( i==3 ) {
        continue;
    }
    System.out.println("关注,点赞,收藏");
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值