白学JA第四天(循环结构)


循环结构的特点:1.循环操作 2.循环结构

while循环

while循环的基本语法格式

while ( 循环条件 ) {

   循环操作

}

public class Demo1 {
    public static void main(String[] args) {
        //1.定义一个变量
        //2.使用变量进行判断,只要满足条件,执行某块代码
        //3.改变变量以改变条件的结果,达到退出循环的目的
        /*int i=1;
        while (i<=10){
            System.out.println("第"+i+"次好好学习天天向上");
            i++;
        }*/
        int a=1;
        while (a<=50){
            System.out.println("打印第"+a+"份试卷");
            a++;
        }
    }
}

do-while循环

do-while循环的基本语法结构

do {

循环操作

}while ( 循环条件 );

public class Demo4 {
    public static void main(String[] args) {
        //先做测试题,老师判断
        //如果不通过,则循环以上的的过程
        Scanner input = new Scanner(System.in);
        /*System.out.println("张浩开始考试!");
        boolean needTest=true;
        while (needTest==true){
            System.out.println("不合格");
            System.out.println("张浩开始考试");
            needTest=input.nextBoolean();
        }
        System.out.println("张浩通过考试");*/
        boolean needTest=false;
        do {
            System.out.println("张浩开始考试");
            System.out.println("请老师给出评价:");
            needTest = input.nextBoolean();
        }while (needTest==true);
    }
}

while和do-while的区别

  • 执行次序不同
  • 初始情况不满足循环条件时:
    while循环一次都不会执行
    do-while循环不管任何情况都至少执行一次

for循环

循环次数固定,for比while更简洁

for循环的语法和执行顺序

for(参数初始化;条件判断;更新循环变量){
循环操作
}

public class Demo5 {
    public static void main(String[] args) {
        int sum=0;
        Scanner input=new Scanner(System.in);
        for (int i=1;i<=5;i++){
            System.out.print("请输入第"+i+"门课成绩:");
            int score=input.nextInt();
            sum += score;
        }
        double avg = (double) sum/5;
        System.out.println("平均分数是:"+avg);
    }
}

总结

共通性

需要多次重复执行一个或多个任务的问题考虑使用循环来解决
无论哪一种循环结构,都有4个必不可少的部分:初始部分、循环条件、循环体、更新循环变量

区别

  • 区别1:语法
  • 区别2:执行顺序
    while 循环:先判断,再执行
    do-while循环:先执行,再判断
    for循环:先判断,再执行
  • 区别3:适用情况
    循环次数确定的情况,通常选用for循环
    循环次数不确定的情况,通常选用while或do-while循环

猜你喜欢

转载自blog.csdn.net/Helltaker/article/details/107235232