Java基础05--喝自己之前偷懒的洗脚水(五)
流程控制2
循环结构
四个要素:
① 初始化部分
② 循环条件部分—是boolean类型
③ 循环体部分
④ 迭代部分
for循环结构
格式:
for(①初始化部分;②循环条件部分;④迭代部分){
③ 循环体部分
}
**执行过程:**① - ②(true) - ③ - ④ - ②(true) - ③ - ④ - … - ②(false) - 退出for循环结构
练习1:
输出5遍“”“Hello World!
//输出5个“Hello World!”
/*
System.out.println("Hello World!");
System.out.println("Hello World!");
System.out.println("Hello World!");
System.out.println("Hello World!");
System.out.println("Hello World!");
*/
for(int i = 1;i <= 5;i++){
System.out.println("Hello World!");
}
//i:在for循环内有效,出了for就无效了
练习2:
int num = 1;
for(System.out.print('a');num <=3;System.out.print('c'),num++){
System.out.print('b');
}
System.out.println();
//输出结果:abcbcbcbc
练习3:
遍历100以内的偶数,输出所有偶数的和,以及偶数的个数
int sum = 0;//记录所有偶数的和
int count = 0;//记录偶数的个数
for(int i = 1;i <= 100;i++){
if(i % 2 == 0){
System.out.println(i);
sum += i;
count++;
}
}
System.out.println("偶数之和为:" + sum);
System.out.println("偶数个数为:" + count);
练习4:
编写程序从1循环到150,并在每行打印一个值,
另外在每个3的倍数行上打印出“foo”,
在每个5的倍数行上打印“biz”,
在每个7的倍数行上打印输出“baz”
class ForTest1 {
public static void main(String[] args) {
for(int i = 1;i <= 150;i++){
System.out.print(i);
if(i % 3 == 0){
System.out.print(" foo");
}
if(i % 5 == 0){
System.out.print(" biz");
}
if(i % 7 == 0){
System.out.print(" baz");
}
//换行
System.out.println();
}
}
}
面试题:
输出所有的水仙花数,所谓水仙花数是指一个3位数,其各个位上数
字立方和等于其本身。
例如: 153 = 111 + 333 + 555
class ForTestShuiXianHuaShu {
public static void main(String[] args) {
for(int i = 100;i < 1000;i++){
int bai = i / 100;
int shi = i / 10 % 10;
int ge = i %10;
int num = bai * bai * bai + shi * shi * shi + ge * ge *ge;
if(i == num){
System.out.println(i);
}
}
}
}
while循环的结构
格式:
①;
while(②){
③;
④;
}
执行过程:① - ②(true) - ③ - ④ - ②(true) - ③ - ④ - … - ②(false) - 退出for循环结构
说明:
1.写while循环千万小心不要丢了迭代条件。一旦丢了,就可能导致死循环。
2.我们写循环,要避免出现死循环
3.for循环和while循环是可以相互转换的!
区别:for循环和while循环的初始化条件部分的作用范围不同。
示例代码:
//遍历100以内的所有偶数
int i = 1;
while(i <= 100){
if(i % 2 == 0){
System.out.println(i);
}
i++;
}
//i 在出了 while 循环后依旧可以调用
System.out.println(i);//101
do-while循环结构
格式:
①;
do{
③;
④;
}while(②);
执行过程:① - ③ - ④ - ②(true) - ③ - ④ - ②(true) - … - ②(false) - 退出for循环结构
说明:
1.do-while循环至少会执行一次循环
2.开发中,使用for或者while更多一些,较少使用do-while
示例代码:
c//遍历100以内所有偶数,并计算它们的和和他们的个数
int i = 1;
int sum = 0;//记录总和
int count = 0;//记录个数
do{
if(i % 2 == 0){
System.out.println(i);
//i++;
/*
编译通过,但无法运行,陷入死循环,
因为初始 i = 1,所以无法进入if结构,
没法进行 i++,也就无法通过while的判定条件
*/
sum += i;
count++;
}
i++;
}while(i <= 100);
System.out.println("总和为:" + sum);
System.out.println("个数为:" + count);
do-while与for、while的不同点:
do-while循环至少会执行一次
int num1 = 10;
while(i < 10){
System.out.println("hello,while");
i--;
}
int num2 = 10;
do{
System.out.println("hello,do-while");
i--;
}while(i < 10);