1500字范文,内容丰富有趣,写作好帮手!
1500字范文 > java 中之循环(for while do-while)详解

java 中之循环(for while do-while)详解

时间:2019-03-25 04:24:14

相关推荐

java 中之循环(for  while  do-while)详解

文章目录

for循环while循环do-while循环

for循环

/*For循环结构的使用一、循环结构的4个要素① 初始化条件② 循环条件 --->是boolean类型③ 循环体④ 迭代条件二、for循环的结构for(①;②;④){③}执行过程:① - ② - ③ - ④ - ② - ③ - ④ - ... - ②*/class ForTest {public static void main(String[] args) {/*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++){//i:1,2,3,4,5System.out.println("Hello World!");}//i:在for循环内有效。出了for循环就失效了。//System.out.println(i);//练习:int num = 1;for(System.out.print('a');num <= 3;System.out.print('c'),num++){System.out.print('b');}//输出结果:abcbcbcSystem.out.println();//例题:遍历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("总和为:" + sum);System.out.println("个数为:" + count);}}

/*编写程序从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();}}}

while循环

/*While 循环的使用一、循环结构的4个要素① 初始化条件② 循环条件 --->是boolean类型③ 循环体④ 迭代条件二、while循环的结构①while(②){③;④;}执行过程:① - ② - ③ - ④ - ② - ③ - ④ - ... - ②说明:1.写while循环千万小心不要丢了迭代条件。一旦丢了,就可能导致死循环!2.我们写程序,要避免出现死循环。3.for循环和while循环是可以相互转换的! 区别:for循环和while循环的初始化条件部分的作用范围不同。算法:有限性。*/class WhileTest{public static void main(String[] args) {//遍历100以内的所有偶数int i = 1;while(i <= 100){if(i % 2 == 0){System.out.println(i);}i++;}//出了while循环以后,仍可以调用。System.out.println(i);//101}}

do-while循环

/*do-while循环的使用一、循环结构的4个要素① 初始化条件② 循环条件 --->是boolean类型③ 循环体④ 迭代条件二、do-while循环结构:①do{③;④;}while(②);执行过程:① - ③ - ④ - ② - ③ - ④ - ... - ②说明:1.do-while循环至少会执行一次循环体!2.开发中,使用for和while更多一些。较少使用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++;}num++;}while(num <= 100);System.out.println("总和为:" + sum);System.out.println("个数为:" + count);//*************体会do-while至少执行一次循环体***************int number1 = 10;while(number1 > 10){System.out.println("hello:while");number1--;}int number2 = 10;do{System.out.println("hello:do-while");number2--;}while(number2 > 10);}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。