练习1:计算0到100之间的奇数和偶数的和
一、循环结构的4个要素
④初始化条件
②循环条件—>是boolean类型
③循环体
④迭代条件
二、do-while循环结构:
①
do{③;④;
}while(②);
执行过程:①-③-④-②-③-④-…-②
说明:do-while循环至少会执行一次循环体!
开发中,使用for和while更多一 些。较少使用do-while。
三 、“无限循环”结构:
while(true) 或for( ; ; )
总结:
如何结束一个循环结构?
方式一:当循环条件是false时
方式二:在循环体中,执行break
boolean isFlag = true;//标志退出
while(isFlag){
isFlag = false
}
嵌套循环:将一个循环结构A声明在另一个循环结构B的循环体中,就构成了嵌套循环。
内层循环:循环结构A
外层循环:循环结构B
说明:
①内层循环结构遍历一遍,只相当于外层循环循环体执行了一次。
②假设外层循环需要执行m次,内层循环需要执行n次。此时内层循环的循环体一共执行了m * n次。
③外层循环控制行数,内层循环控制列数
package com.xin.struct;
public class ForDemo01 {
public static void main(String[] args) {
//while循环
int a = 1; //初始化条件
while(a<100) {//条件判断
System.out.println(a);
a += 2; //迭代 a= a+2
}
System.out.println("while循环结束");
//for循环
//初始化//条件判断//迭代
for(int i =1;i<=100;i++){
System.out.println(i);
}
System.out.println("for循环结束");
}
}
练习2: 用while或for循环输出1-1000之间能被5整除的数,并且每行输出3个
For结构
package com.xin.struct;
public class ForDemo02 {
public static void main(String[] args) {
//输出1000中能够被5整除的数且每行只有三个
for (int i = 5; i <= 1000; i++) {
if(i%5==0){
System.out.print(i+"\t");
}
if(i%(5*3)==0){ //每行
System.out.println("");
}
}
//print()输出后不会换行
//println()输出后会换行
}
}
while结构
package com.xin.struct;
public class WhileDemo03 {
public static void main(String[] args) {
//1000中能够被5除的数
int i = 0;
while (i <= 1000) {
i++;
if (i % 5 == 0) {
System.out.print(i+"\t");
}
if (i % (3 * 5) == 0) {
System.out.println();
}
}
}
}
练习3:打印九九乘法表
package com.xin.struct;
public class ForDemo03 {
//打印一个9*9乘法表
public static void main(String[] args) {
//1.我们先打印第一列
//2.把固定的1,在用一个循环包起来
//3.去掉重复项,i <= j;
//4.调整样式
for (int j = 0; j <= 9; j++) {
for (int i = 1;i<=j;i++){ //9.for 回车快捷键
System.out.print(i+"*"+j+"="+(i*j)+"\t");
}System.out.println();
}
}
}