P1-9 循环结构

循环结构

目的:反复执行N次(或一直执行)某段代码

  • 好比操场上跑圈一样,重复绕圈跑步,直到自己的目标

操场跑圈

DRY原则:Don’t Repeat Yourself.

  • 不要重复你自己,(不要重复复制粘贴代码)
  • 当你发现程序里面有一些代码需要用复制粘贴来重复使用的时候,那就说明你的这个代码是有问题的,需要重构
  • 重构的意思就是说用另外一种算法来把它重新写,而不是把之前的一大堆代码复制粘贴到新的地方去使用
    三种语句:for(重点)、while(次之)、do……while(不讲)

while语句

while

举例:出了什么问题?

问题

1
2
3
4
5
6
7
8
//错误演示
int i =3;
while (i<10);//如果后面加了; 那么i一直=3 就会一直满足如i<10 ,所以一直在死循环 while (i<10){};
{
System.out.println(i);
i++;
}
System.out.println("over");

while案例:

  • 1、从10倒数到0

    1
    2
    3
    4
    5
    6
    int i =10;
    while (i>=0)
    {
    System.out.println(i);
    i--;
    }
  • 2、统计0到10的和

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    //统计0到10的和
    int i = 0;
    int sum =0;
    while (i<=10)
    {
    sum = sum+i;
    System.out.println(" sum="+sum+" i="+i);//输出过程,体验计算的过程
    i++;
    }
    System.out.println(sum);

    while练习

  • 1、用while实现:从5打印到11

1
2
3
4
5
6
int i =5;
while (i<12)
{
System.out.println(i);
i++;
}

for循环结构

既生while何生for

while、do……while、for都可以实现循环,可以互换。
不同需求,用不同语法难易程序不同
使用频率:for > while > do……while

for循环

for循环

1
2
3
4
for(表达式1;表达式2;表达式3)
{
循环体
}

原理:
(1)先执行表达式1,只会执行一次
(2)执行表达式2,如果该表达式2结果为真,执行for循环体,然后执行下面第(3)步;如果为假,直接结束for循环
(3)执行表达式3,然后跳到第(2)步重新执行

最常用用法

1
2
3
4
5
for (int i =0;i<=3;i++)
{
System.out.println(i);
}
int i =0;

上面的例子用while语句去理解

1
2
3
4
5
6
int i =0;
while (i<=3)
{
System.out.println(i);
i++;
}

细节-作用域

区别在于作用域;for循环内定义变量的作用域问题

1
2
3
4
5
int i=0;
for (i=0;i<=3;i++)//里面的i=0,是引用了上面声明的变量i了
{
System.out.println(i);
}

for案例

初始逻辑是什么;
循环条件式什么;
每次循环之后干什么;

  • 1、从10倒数到0

    初始逻辑 int i=10
    循环条件 i>=0
    每次循环后的动作 i–

1
2
3
4
for (int i=10;i>=0;i--)
{
System.out.println(i);
}
  • 2、统计0到10的和
1
2
3
4
5
6
int sum =0;
for (int i =0;i<=10;i++)
{
sum=sum+i;
}
System.out.println(sum);
  • 3、输出2,4,6,8,10
1
2
3
4
for (int i =2;i<=10;i=i+2)
{
System.out.println(i);
}

练习

  • 1、用for实现:从5打印到11

    初始逻辑 int i=5
    循环条件 i<=11
    每次循环后的动作 i++

1
2
3
4
for (int i=5;i<=11;i++)
{
System.out.println(i);
}

循环结构其他用法

循环嵌套:循环里套着循环。原地转一圈,就跑一步。
嵌套循环可以是嵌套N层,但一般两层

三种循环(while、do……while、for)可以互相嵌套
不过使用最多的是for循环嵌套

for循环嵌套

for循环嵌套

  • 练习
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
     for (int i=0;i<3;i++)
    {
    System.out.println("进入内循环");
    for (int j=1;j<=3;j++)
    {
    System.out.println(i+","+j);
    }
    System.out.println("内循环结束");
    }


break和continue

  • 1、break和continue都可以和while、do while、for 一起用
  • 2、break:强制结束循环
  • 3、continue:不再执行本次循环后面的代码,进行下一次循环

break和continue

1
2
3
4
5
6
7
8
9
for (int i = 0;i<=10;i++)
{
if (i%2==0)
{
break;
//continue;
}
System.out.println(i);
}

大道至简


P1-9 循环结构
http://example.com/2024/08/01/SE101-零基础玩Java/Part1-笔记/P1-9 循环结构/
Author
John Doe
Posted on
August 1, 2024
Licensed under