开发者学堂课程【【名师课堂】Java 零基础入门:程序逻辑控制(循环结构)】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/370/detail/4416
程序逻辑控制(循环结构)
内容简介:
一、while 循环
二、for 循环
三、循环使用原则
循环结构指的是某几行代码被重复执行的操作。循环分为两类循环:while 循环、for 循环。
一、 while 循环
1、while 循环语法(两种):
循环的初始化内容
while(循环的结束条件判断) {
循环语句 ;
修改循环结束条件判断 ;
}
循环的初始化内容
do {
循环语句 ;
修改循环结束条件判断 ;
while(循环的结束条件判断) ;
}
使用 while 循环的最大特点:如果判断条件不满足就一次也不执行;
使用 do while 的特点:即使判断条件不满足也会执行一次
2、while 循环操作
范例:使用 while 实现1~100的累加
public class TestDemo {
public static void main (String args [ ]) {
int num = 1 ;
int result = 0 ;
while (num <= 100) { 现在表示为循环的结束条件
result += num ++ ;
num ++ ; 循环条件变更
}
System.out.println(result) ;
}
}
3、使用 do while 进行操作
范例:使用 do while 实现累加处理
public class TestDemo {
public static void main (String args [ ]) {
int num = 1 ;
int result = 0 ;
do {
result += num ++ ;
num ++ ; 循环条件变更
} while (num <= 100);
System.out.println(result) ;
}
}
以后的开发对于 do while 基本不使用。
二、for 循环
1、for 循环语法
for(循环初始化条件 ;循环结束判断;修改循环条件) {
循环体代码 ;
}
2、范例:使用 for 循环实现1~100的累加
public class TestDemo {
public static void main (String args [ ]) {
int result = 0 ;
(1)循环初始化: int x = 0 ;
(2)判断循环条件: x <= 100 ;
(4)循环条件变更: x ++
(5)判断循环条件: 在(2)(3)(4)(5)之间循环
for (int x = 0 ; x <= 100 ; x ++) {
result += x ; (3)循环体操作
}
System.out.println (result) ;
}
}
三、循环使用原则:
•对于不知道循环次数但知道循环结束条件的情况,使用 while 循环;
•如果已经明确知道循环次数,则使用 for 循环。