------- android培训、java培训、期待与您交流! ----------
循环结构:
代表语句:while ,do while ,for
while语句格式 :
while(条件表达式)
{
执行语句;
}
do while语句格式:
do
{
执行语句;
}
while(条件表达式);
do while特点是条件无论是否满足,循环体至少被执行一次。
for语句格式:
for(初始化表达式;循环条件表达式;循环后的操作表达式)
{
执行语句;
}
a,for里面的连个表达式运行的顺序,初始化表达式只读一次,判断循环条件,为真就执行循环体,然后再执行循环后的操作表达式,接着继续判断循环条件,重复找个过程,直到条件不满足为止。
b,while与for可以互换,区别在于for为了循环而定义的变量在for循环结束就是在内存中释放。而while循环使用的变量在循环结束后还可以继续使用。
c,最简单无限循环格式:while(true) , for( ; ; ),无限循环存在的原因是并不知道循环多少次,而是根据某些条件,来控制循环。
如何选择用while还是for?
for和while可以进行互换。但是如果需要定义循环增量。用for更为合适。
什么时候使用循环结构? 当要对某些语句执行很多次时,就使用循环结构。
程序练习:
/** * 需求:用while,do while和for循环算出1+10的结果 * *思路:累加原理 */ public class WhileDemo { public static void main(String [] args) { //while example int i = 1,sum = 0; while(i<=10) { sum+=i; i++; } System.out.println(sum); //do while example int sum1 = 0; --i; do { sum1+=i; i--; } while(i>=1); System.out.println(sum1); //for example int sum2 = 0; for (int x=1;x<=10;x++) { sum2+=x; } System.out.println(sum2); } }
/** * 需求:打印1~100之间7的倍数的个数 * * 思路:需要用到循环语句,计数器思想 * 遍历1~100 * 凡是%7为0的就是7的倍数 * */ public class XunHuan1 { public static void main(String [] args) { int count = 0; for(int i=1;i<=100;i++) { if(i%7==0) count++; } System.out.println(count); } }
for语句循环嵌套的练习:发现图形有很多行,每一个行有很多列。要使用嵌套循环
/** * 需求:打印图形: * * ****** * ***** * **** * *** * ** * * * * * ** * *** * **** * ***** * ****** * * 思路:符合大圈套小圈的思想,应该使用循环嵌套 * 定义横排个数为x,纵排为y, * 发现x从6递减到1再递增到6 * y由x从6到1用了6行 * 后半部分是上半部分的翻转 * */ public class XunHuan2 { public static void main(String [] args) { for (int y=0;y<6;y++) { for (int x=0;x<6-y;x++) { System.out.print("*"); } System.out.println(); } for (int y=0;y<6;y++) { for (int x=0;x<y+1;x++) { System.out.print("*"); } System.out.println(); } } }
/** * * 需求:打印下图三角 * * * * * * * * * * * * * * * * * * * * * * 思路:符合大圈套小圈思想,用循环嵌套 * 定义横排x,竖排y * 发现个数递增 * * 实际图形 * -----* * ----** * ---*** * --**** * -***** * * */ public class XunHuan3 { public static void main(String [] args) { for (int y=0;y<5;y++) { for(int x=0;x<5-y;x++) { System.out.print(" "); } for(int z=0;z<y+1;z++) { System.out.print("* "); } System.out.println(); } } }
/** * *需求:打印一个99乘法表 * *思路:符合大圈套小圈思想,用循环嵌套 * 定义x为被乘数,y为乘数。 * * */ public class XunHuan4 { public static void main(String [] args) { for (int y=1;y<=9;y++) { for (int x=1;x<=y;x++) { System.out.print(x+"*"+y+"="+(x*y)+" "); } System.out.println(); } } }
其他流程控制语句:
break( 跳出) ,
continue( 继续)
break语句:应用范围:选择结构和循环结构。
continue语句:应用于循环结构。
注:
a,这两个语句离开应用范围,存在是没有意义的。
b,这个两个语句单独存在下面都不可以有语句,因为执行不到。
c,continue语句是结束本次循环继续下次循环。
d,标号的出现,可以让这两个语句作用于指定的范围。
------- android培训、java培训、期待与您交流! ----------