/*
while结构的使用:
1.循环结构的四个要素:
初始化条件
循环条件(布尔类型)
循环体
迭代条件
2.while循环的结构
初始化条件
while(循环条件){
循环体
迭代条件
}
3.说明:
(1)写while循环千万不要丢了迭代条件,一旦丢了,就可能造成死循环!
(2)我们写程序,要避免出现死循环
(3)for循环与while循环可以相互转化(定义的变量有在for循环内部的部分与while循环外部的部分的区别)
4.执行过程:初始化条件-->循环条件-->迭代条件-->循环体-->循坏条件-->…………
*/
class WhileTest{
public static void main(String[] args){
//遍历100以内的所有偶数
int i=1;
while(i<=100){
if(i%2==0){
System.out.println(i);
}
i++;
}
}
}
/*
do-while循坏的使用
1.循环结构的四个要素:
初始化条件
循环条件(布尔类型)
循环体
迭代条件
2.do-while循环的结构
初始化条件
do{
循环体;
迭代条件;
}while(循环条件);
执行过程:初始化条件-->循环体-->迭代条件-->循环条件-->循环体-->…………
3.说明:
(1)do-while循环至少执行一次
*/
class DoWhileTest{
public static void main(String[] args){
//遍历100以内的偶数,并计算所有偶数的和及个数
int num=1;
int sum=0;//记录总和
int count=0;//记录个数
do{
if(num%2==0){
System.out.println(num);
sum+=num;
count++;//count++与++count没有区别
}
num++;
}
while(num<=100);
System.out.println("总和为:"+sum);
System.out.println("总个数为:"+count);
}
}